import { Card, Col, Container, Row } from 'react-bootstrap';
import { Head, usePage, router } from '@inertiajs/react';
import React, { useEffect, useRef } from 'react';
import Swal from 'sweetalert2';
import Layout from '../../../../Layouts';
import { useLoading } from '../../../../LoadingContext';
import TarifasCardsView from './TarifasCardsView';

const Index = () => {
  const { tarifas, pagination, tipoTarifa } = usePage().props as any;
  const flash = usePage().props.flash as any;
  const flashShownRef = useRef<string | null>(null);

  useEffect(() => {
    const msg = flash?.message || flash?.error;
    if (!msg || flashShownRef.current === msg) return;
    flashShownRef.current = msg;
    Swal.fire({
      title: msg,
      icon: flash?.type || (flash?.error ? 'error' : 'success'),
      timer: 1500,
      showConfirmButton: false,
    });
  }, [flash]);
  const initialData = Array.isArray(tarifas) ? tarifas : [];
  const initialPagination = pagination || { current_page: 1, last_page: 1, per_page: 12, total: initialData.length };
  const tipo = (tipoTarifa === 'gas' ? 'gas' : 'electrica') as 'electrica' | 'gas';
  const { showLoading, hideLoading } = useLoading();

  const handleAgregar = (tipoTarifaSeleccionado: 'electrica' | 'gas') => {
    showLoading();
    router.visit(route('tarifas.crear', { tipo: tipoTarifaSeleccionado }), { onFinish: hideLoading });
  };

  return (
    <React.Fragment>
      <Head title="Tarifas" />
      <div className="page-content">
        <Container fluid>
          <Row className="mb-3">
            <Col className="d-flex justify-content-end">
              <button
                type="button"
                className="btn btn-sm"
                style={{ minWidth: 180, fontWeight: 500, background: '#fff7e6', border: '2px solid orange', color: 'orange' }}
                onClick={() => handleAgregar(tipo)}
                aria-label="Agregar nueva tarifa"
              >
                <i className="fas fa-bolt me-2" aria-hidden="true" />
                Agregar Tarifa
              </button>
            </Col>
          </Row>
          <Row>
            <Col lg={12}>
              <Card>
                <Card.Header><h5 className="card-title mb-0">Tarifas</h5></Card.Header>
                <Card.Body>
                  <TarifasCardsView
                    initialItems={initialData}
                    initialPagination={initialPagination}
                    tipoTarifaInicial={tipo}
                    flash={flash}
                    onAgregar={handleAgregar}
                  />
                </Card.Body>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    </React.Fragment>
  );
};

Index.layout = (page: any) => <Layout children={page} />;
export default Index;
