'use client';

import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Switch } from '@/components/ui/switch';
import { Loader2, Search } from 'lucide-react';
import { RateFiltersPanel } from '@/components/rate-search/RateFiltersPanel';
import { RateResultsTable } from '@/components/rate-search/RateResultsTable';
import { useCsvRateSearch } from '@/hooks/useCsvRateSearch';
import type { RateSearchFilters } from '@/types/rate-filters';
import type { CsvRateSearchResult } from '@/types/rates';

export default function CsvRateSearchPage() {
  const [origin, setOrigin] = useState('FRFOS');
  const [destination, setDestination] = useState('CNSHA');
  const [volumeCBM, setVolumeCBM] = useState(10);
  const [weightKG, setWeightKG] = useState(2500);
  const [hasDangerousGoods, setHasDangerousGoods] = useState(false);
  const [filters, setFilters] = useState<RateSearchFilters>({});

  const { data, loading, error, search } = useCsvRateSearch();

  const handleSearch = async () => {
    await search({
      origin,
      destination,
      volumeCBM,
      weightKG,
      containerType: 'LCL',
      hasDangerousGoods,
      filters,
    });
  };

  const handleBooking = (result: CsvRateSearchResult) => {
    alert(
      `Réservation pour ${result.companyName}\nContact : ${result.companyEmail}\nRoute : ${result.originCFS} → ${result.destinationCFS}`
    );
  };

  return (
    <div className="container mx-auto py-8 space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Comparateur de tarifs LCL</h1>
        <p className="text-muted-foreground mt-2">
          Comparez les tarifs de fret maritime LCL multi-fournisseurs avec détail FOB et fret
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Filtres */}
        <div className="lg:col-span-1">
          <RateFiltersPanel
            filters={filters}
            onFiltersChange={setFilters}
            resultsCount={data?.totalResults || 0}
            onReset={() => setFilters({})}
          />
        </div>

        {/* Formulaire + résultats */}
        <div className="lg:col-span-3 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Paramètres de recherche</CardTitle>
              <CardDescription>
                Indiquez votre trajet, volume et poids pour obtenir des tarifs comparés
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Origine / Destination */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="origin">
                    Port d'origine <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="origin"
                    value={origin}
                    onChange={e => setOrigin(e.target.value.toUpperCase())}
                    placeholder="FRFOS"
                    maxLength={5}
                  />
                  <p className="text-xs text-muted-foreground">Code UN/LOCODE (ex: FRFOS, FRLEH)</p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="destination">
                    Port de destination <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="destination"
                    value={destination}
                    onChange={e => setDestination(e.target.value.toUpperCase())}
                    placeholder="CNSHA"
                    maxLength={5}
                  />
                  <p className="text-xs text-muted-foreground">Code UN/LOCODE (ex: CNSHA, USNYC)</p>
                </div>
              </div>

              {/* Volume / Poids */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="volume">
                    Volume (CBM) <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="volume"
                    type="number"
                    min={0.1}
                    step={0.1}
                    value={volumeCBM}
                    onChange={e => setVolumeCBM(parseFloat(e.target.value) || 0)}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="weight">
                    Poids (kg) <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="weight"
                    type="number"
                    min={1}
                    step={100}
                    value={weightKG}
                    onChange={e => setWeightKG(parseInt(e.target.value, 10) || 0)}
                  />
                </div>
              </div>

              {/* Marchandises dangereuses */}
              <div className="flex items-center space-x-2">
                <Switch
                  id="dg"
                  checked={hasDangerousGoods}
                  onCheckedChange={setHasDangerousGoods}
                />
                <Label htmlFor="dg" className="cursor-pointer">
                  Marchandises dangereuses (DG)
                </Label>
              </div>

              {/* Recherche */}
              <Button
                onClick={handleSearch}
                disabled={loading || !origin || !destination || volumeCBM <= 0 || weightKG <= 0}
                className="w-full"
                size="lg"
              >
                {loading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Recherche en cours...
                  </>
                ) : (
                  <>
                    <Search className="mr-2 h-4 w-4" />
                    Comparer les tarifs
                  </>
                )}
              </Button>
            </CardContent>
          </Card>

          {error && (
            <Alert variant="destructive">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {data && (
            <Alert>
              <AlertDescription>
                {new Date(data.searchedAt).toLocaleString('fr-FR')} — {data.searchedFiles.length}{' '}
                fournisseur(s) analysé(s) — {data.totalResults} tarif(s) trouvé(s)
              </AlertDescription>
            </Alert>
          )}

          {data && data.results.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Résultats de comparaison</CardTitle>
                <CardDescription>
                  {data.totalResults} tarif{data.totalResults > 1 ? 's' : ''} — prix = Fret + Frais
                  FOB (deux devises possibles)
                </CardDescription>
              </CardHeader>
              <CardContent>
                <RateResultsTable results={data.results} onBooking={handleBooking} />
              </CardContent>
            </Card>
          )}

          {data && data.results.length === 0 && (
            <Card>
              <CardContent className="py-12 text-center">
                <p className="text-muted-foreground">Aucun tarif trouvé pour cette route.</p>
                <p className="text-sm text-muted-foreground mt-2">
                  Vérifiez les codes UN/LOCODE saisis (ex: FRFOS, CNSHA).
                </p>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
