'use client';

import { useState, useEffect } from 'react';
import { Edit, Trash2, Search } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { getTariffRef } from './constants';
import type { SeatClass, CoachType } from './types';

interface Props {
  classes: SeatClass[];
  coachTypes: CoachType[];
  isLoading: boolean;
  onEdit: (cls: SeatClass) => void;
  onDelete: (id: string, cascade: boolean) => void;
  isDeleting: boolean;
  deleteError?: string;
  deleteSuccess?: number;
}

export default function TariffTab({ classes, coachTypes, isLoading, onEdit, onDelete, isDeleting, deleteError, deleteSuccess }: Props) {
  const [search, setSearch] = useState('');
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    item: SeatClass | null;
    cascade: boolean;
    cascadeChecked: boolean;
    error?: string;
  }>({ isOpen: false, item: null, cascade: false, cascadeChecked: false });

  // Close dialog on successful delete
  useEffect(() => {
    if (!deleteSuccess) return;
    setDeleteConfirm({ isOpen: false, item: null, cascade: false, cascadeChecked: false });
  }, [deleteSuccess]); // eslint-disable-line react-hooks/exhaustive-deps

  // Sync external error into dialog when it arrives
  useEffect(() => {
    if (!deleteError || !deleteConfirm.isOpen) return;
    setDeleteConfirm(prev => ({
      ...prev,
      cascade: prev.cascade || deleteError.includes('Cannot delete'),
      cascadeChecked: false,
      error: deleteError,
    }));
  }, [deleteError]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleDeleteClick = (cls: SeatClass) => {
    setDeleteConfirm({ isOpen: true, item: cls, cascade: false, cascadeChecked: false, error: undefined });
  };

  const handleConfirm = () => {
    onDelete(deleteConfirm.item!.id, deleteConfirm.cascade && deleteConfirm.cascadeChecked);
  };

  const displayed = classes
    .filter(c => c.nationalityType)
    .filter(c => {
      if (!search) return true;
      const s = search.toLowerCase();
      const ct = coachTypes.find(t => t.id === c.coachTypeId);
      return (
        c.name?.toLowerCase().includes(s) ||
        c.nationalityType?.toLowerCase().includes(s) ||
        c.bedPosition?.toLowerCase().includes(s) ||
        ct?.name?.toLowerCase().includes(s)
      );
    })
    .sort((a, b) => (a.nationalityType === b.nationalityType ? 0 : a.nationalityType === 'LOCAL' ? -1 : 1));

  const columns = [
    {
      key: 'nationalityType', label: 'Passenger Type',
      render: (c: SeatClass) => (
        <Badge variant="status" status={c.nationalityType === 'LOCAL' ? 'CONFIRMED' : 'INFO'}>
          {c.nationalityType === 'LOCAL' ? 'Local' : 'International'}
        </Badge>
      ),
    },
    {
      key: 'coachType', label: 'Coach Type',
      render: (c: SeatClass) => {
        const ct = coachTypes.find(t => t.id === c.coachTypeId);
        return <span className="text-sm">{ct ? `${ct.code} — ${ct.name}` : c.coachTypeId}</span>;
      },
    },
    {
      key: 'name', label: 'Class Name',
      render: (c: SeatClass) => <span className="font-medium">{c.name}</span>,
    },
    {
      key: 'baseFareMinor', label: 'Rate per km',
      render: (c: SeatClass) => {
        const ct = coachTypes.find(t => t.id === c.coachTypeId);
        const ref = ct ? getTariffRef(c.nationalityType!, ct.code, c.bedPosition ?? null) : undefined;
        const tariffMinor = ref ? Math.round(ref * 100) : undefined;
        const matches = tariffMinor === c.baseFareMinor;
        return (
          <div className="flex items-center gap-2">
            <span className="font-mono font-medium">{c.baseFareMinor! / 100}</span>
            {tariffMinor !== undefined && (
              <span className={`text-xs px-1.5 py-0.5 rounded ${matches ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400'}`}>
                {matches ? '✓ tariff' : `tariff: ${tariffMinor / 100}`}
              </span>
            )}
          </div>
        );
      },
    },
    {
      key: 'insuranceFeeMinor', label: 'Insurance Fee',
      render: (c: SeatClass) => (
        <span className="font-mono text-sm">{c.insuranceFeeMinor ? (c.insuranceFeeMinor / 100).toFixed(2) : '0.00'} ETB</span>
      ),
    },
    {
      key: 'isActive', label: 'Status',
      render: (c: SeatClass) => (
        <Badge variant="status" status={c.isActive ? 'CONFIRMED' : 'CANCELLED'}>
          {c.isActive ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
  ];

  return (
    <>
      <div className="relative mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <input
          type="text"
          placeholder="Search by name, nationality, etc."
          className="input pl-10 w-full"
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>

      <DataTable
        data={displayed}
        columns={columns}
        actions={[
          { label: 'Edit', icon: Edit, variant: 'secondary' as const, onClick: onEdit },
          { label: 'Delete', icon: Trash2, variant: 'danger' as const, onClick: handleDeleteClick },
        ]}
        loading={isLoading}
        emptyMessage={search ? 'No tariff rates match your search' : 'No tariff rates found'}
      />

      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, item: null, cascade: false, cascadeChecked: false })}
        onConfirm={handleConfirm}
        title="Delete Tariff Rate"
        message={`Delete "${deleteConfirm.item?.name}"? This will affect fare calculations for this class.`}
        confirmText="Delete"
        isDanger
        isLoading={isDeleting}
        error={deleteConfirm.error}
        warning={!deleteConfirm.cascade
          ? 'This seat class may be referenced by fare rules, route overrides, and segment fares. Deleting it will impact pricing across all routes.'
          : undefined}
        cascadeWarning={deleteConfirm.cascade
          ? 'This seat class has related fare rules, route overrides, or segment fares that will also be permanently deleted.'
          : undefined}
        cascadeChecked={deleteConfirm.cascadeChecked}
        onCascadeChange={checked => setDeleteConfirm(prev => ({ ...prev, cascadeChecked: checked }))}
      />
    </>
  );
}
