'use client';

import { useState } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { ArrowUpDown, Info, Mail, AlertTriangle } from 'lucide-react';
import type { CsvRateSearchResult, ServiceLevel } from '@/types/rates';

interface RateResultsTableProps {
  results: CsvRateSearchResult[];
  onBooking?: (result: CsvRateSearchResult) => void;
}

type SortField = 'price' | 'transit' | 'company' | 'matchScore';
type SortOrder = 'asc' | 'desc';

const SERVICE_LEVEL_LABELS: Record<ServiceLevel, { label: string; color: string }> = {
  ECONOMIC: { label: 'Éco', color: 'bg-green-100 text-green-800 border-green-200' },
  STANDARD: { label: 'Standard', color: 'bg-blue-100 text-blue-800 border-blue-200' },
  RAPID: { label: 'Rapide', color: 'bg-orange-100 text-orange-800 border-orange-200' },
};

const FREQUENCY_BADGE: Record<string, string> = {
  Weekly: 'bg-emerald-100 text-emerald-700',
  'Bi-Weekly': 'bg-sky-100 text-sky-700',
  'Bi-Monthly': 'bg-amber-100 text-amber-700',
  Monthly: 'bg-rose-100 text-rose-700',
};

export function RateResultsTable({ results, onBooking }: RateResultsTableProps) {
  const [sortField, setSortField] = useState<SortField>('price');
  const [sortOrder, setSortOrder] = useState<SortOrder>('asc');

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('asc');
    }
  };

  const sortedResults = [...results].sort((a, b) => {
    let aVal: number | string;
    let bVal: number | string;

    switch (sortField) {
      case 'price':
        aVal = a.priceBreakdown.totalPriceForSorting;
        bVal = b.priceBreakdown.totalPriceForSorting;
        break;
      case 'transit':
        aVal = a.transitDays;
        bVal = b.transitDays;
        break;
      case 'company':
        aVal = a.companyName;
        bVal = b.companyName;
        break;
      case 'matchScore':
        aVal = a.matchScore;
        bVal = b.matchScore;
        break;
      default:
        return 0;
    }

    return sortOrder === 'asc' ? (aVal > bVal ? 1 : -1) : aVal < bVal ? 1 : -1;
  });

  const SortButton = ({ field, label }: { field: SortField; label: string }) => (
    <button
      onClick={() => handleSort(field)}
      className="flex items-center gap-1 hover:text-primary transition-colors"
    >
      {label}
      <ArrowUpDown className="h-4 w-4" />
    </button>
  );

  if (results.length === 0) {
    return (
      <div className="text-center py-12 border rounded-lg">
        <p className="text-muted-foreground">Aucun tarif trouvé pour cette recherche.</p>
        <p className="text-sm text-muted-foreground mt-2">
          Essayez d'ajuster vos critères de recherche ou vos filtres.
        </p>
      </div>
    );
  }

  return (
    <div className="rounded-md border overflow-x-auto">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>
              <SortButton field="company" label="Fournisseur" />
            </TableHead>
            <TableHead>Niveau</TableHead>
            <TableHead>Route</TableHead>
            <TableHead>Routing</TableHead>
            <TableHead>Fréquence</TableHead>
            <TableHead>
              <SortButton field="price" label="Prix estimé" />
            </TableHead>
            <TableHead>
              <SortButton field="transit" label="Transit" />
            </TableHead>
            <TableHead>Validité</TableHead>
            <TableHead>DG</TableHead>
            <TableHead>
              <SortButton field="matchScore" label="Score" />
            </TableHead>
            <TableHead>Actions</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {sortedResults.map((result, index) => {
            const bd = result.priceBreakdown;
            const sl = result.serviceLevel as ServiceLevel | undefined;
            const slInfo = sl ? SERVICE_LEVEL_LABELS[sl] : null;

            return (
              <TableRow key={index}>
                {/* Fournisseur */}
                <TableCell>
                  <div className="font-medium text-sm">{result.companyName}</div>
                  <div className="text-xs text-muted-foreground flex items-center gap-1">
                    <Mail className="h-3 w-3" />
                    {result.companyEmail}
                  </div>
                </TableCell>

                {/* Niveau de service */}
                <TableCell>
                  {slInfo ? (
                    <span
                      className={`text-xs font-medium px-2 py-1 rounded border ${slInfo.color}`}
                    >
                      {slInfo.label}
                      {result.priceMultiplier && result.priceMultiplier !== 1 && (
                        <span className="ml-1 opacity-70">
                          {result.priceMultiplier > 1 ? '+' : ''}
                          {Math.round((result.priceMultiplier - 1) * 100)}%
                        </span>
                      )}
                    </span>
                  ) : (
                    <span className="text-xs text-muted-foreground">—</span>
                  )}
                </TableCell>

                {/* Route */}
                <TableCell>
                  <div className="text-sm font-medium">{result.originCFS || result.origin}</div>
                  <div className="text-xs text-muted-foreground">
                    → {result.destinationCFS || result.destination}
                  </div>
                  <div className="text-xs text-muted-foreground">
                    ({result.origin} / {result.destination})
                  </div>
                </TableCell>

                {/* Routing */}
                <TableCell>
                  <Badge
                    variant="outline"
                    className={
                      result.routing.toLowerCase() === 'direct'
                        ? 'border-green-500 text-green-700'
                        : 'border-amber-500 text-amber-700'
                    }
                  >
                    {result.routing}
                  </Badge>
                  {result.portOfLoading && result.portOfLoading !== result.origin && (
                    <div className="text-xs text-muted-foreground mt-1">
                      via {result.portOfLoading}
                    </div>
                  )}
                </TableCell>

                {/* Fréquence */}
                <TableCell>
                  <span
                    className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                      FREQUENCY_BADGE[result.frequency] || 'bg-gray-100 text-gray-700'
                    }`}
                  >
                    {result.frequency}
                  </span>
                </TableCell>

                {/* Prix */}
                <TableCell>
                  <PriceCell result={result} />
                </TableCell>

                {/* Transit */}
                <TableCell>
                  <div className="text-sm font-medium">{result.transitDays} j</div>
                  {result.originalTransitDays &&
                    result.originalTransitDays !== result.transitDays && (
                      <div className="text-xs text-muted-foreground line-through">
                        {result.originalTransitDays} j
                      </div>
                    )}
                </TableCell>

                {/* Validité */}
                <TableCell>
                  <div className="text-xs text-muted-foreground">
                    {new Date(result.validUntil).toLocaleDateString('fr-FR')}
                  </div>
                </TableCell>

                {/* DG */}
                <TableCell>
                  {!result.dgAccepted ? (
                    <span title="DG non accepté" className="text-red-500">
                      <AlertTriangle className="h-4 w-4" />
                    </span>
                  ) : result.dgSurchargeStatus === 'on_request' ? (
                    <Badge variant="outline" className="text-xs border-amber-400 text-amber-700">
                      Sur devis
                    </Badge>
                  ) : (
                    <Badge variant="outline" className="text-xs border-green-400 text-green-700">
                      Accepté
                    </Badge>
                  )}
                </TableCell>

                {/* Score */}
                <TableCell>
                  <span
                    className={`text-sm font-medium ${
                      result.matchScore >= 105
                        ? 'text-green-600'
                        : result.matchScore >= 95
                          ? 'text-blue-600'
                          : 'text-gray-500'
                    }`}
                  >
                    {result.matchScore}
                  </span>
                </TableCell>

                {/* Actions */}
                <TableCell>
                  <Button size="sm" onClick={() => onBooking?.(result)} disabled={!onBooking}>
                    Réserver
                  </Button>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>

      <div className="p-4 border-t bg-muted/50 text-sm text-muted-foreground">
        {results.length} tarif{results.length > 1 ? 's' : ''} trouvé{results.length > 1 ? 's' : ''}{' '}
        — Prix estimés : Fret (USD/EUR) + FOB (EUR). Les devises peuvent différer selon le
        fournisseur.
      </div>
    </div>
  );
}

function PriceCell({ result }: { result: CsvRateSearchResult }) {
  const bd = result.priceBreakdown;

  return (
    <Dialog>
      <DialogTrigger asChild>
        <button className="text-left hover:underline group">
          <div className="font-semibold text-sm">
            {bd.freightCurrency} {bd.totalFreight.toFixed(0)}
            <span className="text-muted-foreground font-normal text-xs ml-1">fret</span>
          </div>
          <div className="text-xs text-muted-foreground">
            + {bd.fobCurrency} {bd.totalFob.toFixed(0)} FOB
          </div>
          <div className="flex items-center gap-1 text-xs text-blue-600 group-hover:underline">
            <Info className="h-3 w-3" />
            Détail
          </div>
        </button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Détail du prix estimé</DialogTitle>
          <DialogDescription>
            {result.companyName} — {result.originCFS || result.origin} →{' '}
            {result.destinationCFS || result.destination}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-2">
          {/* Fret */}
          <div>
            <h4 className="font-medium text-sm mb-2">Fret ({bd.freightCurrency})</h4>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">Taux de fret</span>
              <span>
                {bd.freightCurrency} {bd.freightCharge.toFixed(2)}
              </span>
            </div>
          </div>

          {/* FOB */}
          <div>
            <h4 className="font-medium text-sm mb-2">Frais FOB ({bd.fobCurrency})</h4>
            <div className="space-y-1 text-sm">
              {bd.fobBreakdown.documentation > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Documentation</span>
                  <span>{bd.fobBreakdown.documentation}</span>
                </div>
              )}
              {bd.fobBreakdown.isps > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">ISPS</span>
                  <span>{bd.fobBreakdown.isps}</span>
                </div>
              )}
              {bd.fobBreakdown.handling > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Manutention</span>
                  <span>{bd.fobBreakdown.handling.toFixed(2)}</span>
                </div>
              )}
              {bd.fobBreakdown.solas > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">SOLAS</span>
                  <span>{bd.fobBreakdown.solas}</span>
                </div>
              )}
              {bd.fobBreakdown.customs > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Douane export</span>
                  <span>{bd.fobBreakdown.customs}</span>
                </div>
              )}
              {bd.fobBreakdown.ams_aci > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">AMS/ACI</span>
                  <span>{bd.fobBreakdown.ams_aci}</span>
                </div>
              )}
              {bd.fobBreakdown.isf5 > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">ISF5</span>
                  <span>{bd.fobBreakdown.isf5}</span>
                </div>
              )}
              {bd.fobBreakdown.dgAdmin > 0 && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Admin DG</span>
                  <span>{bd.fobBreakdown.dgAdmin}</span>
                </div>
              )}
            </div>
          </div>

          {/* DG surcharge if applicable */}
          {bd.dgSurchargeStatus === 'on_request' && (
            <div className="rounded bg-amber-50 border border-amber-200 px-3 py-2 text-sm text-amber-800">
              Surcharge DG : sur demande — contactez le fournisseur
            </div>
          )}
          {bd.dgSurchargeStatus === 'not_accepted' && (
            <div className="rounded bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-800">
              DG non accepté sur cette route
            </div>
          )}
          {bd.dgSurchargeAmount !== null && bd.dgSurchargeAmount > 0 && (
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">Surcharge DG ({bd.dgSurchargeCurrency})</span>
              <span>{bd.dgSurchargeAmount.toFixed(2)}</span>
            </div>
          )}

          {/* Totals */}
          <div className="border-t pt-3 space-y-1">
            <div className="flex justify-between text-sm font-medium">
              <span>Total Fret</span>
              <span>
                {bd.freightCurrency} {bd.totalFreight.toFixed(2)}
              </span>
            </div>
            <div className="flex justify-between text-sm font-medium">
              <span>Total FOB</span>
              <span>
                {bd.fobCurrency} {bd.totalFob.toFixed(2)}
              </span>
            </div>
            {bd.freightCurrency !== bd.fobCurrency && (
              <p className="text-xs text-muted-foreground mt-2">
                ⚠ Le fret est en {bd.freightCurrency} et le FOB en {bd.fobCurrency}. Un taux de
                change est nécessaire pour le total exact.
              </p>
            )}
          </div>

          {/* Contact */}
          <div className="border-t pt-3">
            <p className="text-xs text-muted-foreground">
              Contact booking :{' '}
              <a href={`mailto:${result.companyEmail}`} className="text-primary hover:underline">
                {result.companyEmail}
              </a>
            </p>
            {result.remarks && (
              <p className="text-xs text-muted-foreground mt-1">Ref: {result.remarks}</p>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
