/**
 * CSV Upload Component (ADMIN only)
 *
 * Upload CSV rate files for carrier companies
 * Protected: Only accessible to users with ADMIN role
 */

'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Upload, CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { uploadCsvRates } from '@/lib/api/admin/csv-rates';

export function CsvUpload() {
  const router = useRouter();
  const [companyName, setCompanyName] = useState('');
  const [companyEmail, setCompanyEmail] = useState('');
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0] || null;
    setFile(selectedFile);
    setError(null);
    setSuccess(null);

    // Validate file type
    if (selectedFile && !selectedFile.name.endsWith('.csv')) {
      setError('Seuls les fichiers CSV (.csv) sont acceptés');
      setFile(null);
    }

    // Validate file size (10MB max)
    if (selectedFile && selectedFile.size > 10 * 1024 * 1024) {
      setError('Le fichier ne doit pas dépasser 10 MB');
      setFile(null);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!file || !companyName || !companyEmail) {
      setError('Veuillez remplir tous les champs');
      return;
    }

    setLoading(true);
    setError(null);
    setSuccess(null);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('companyName', companyName);
      formData.append('companyEmail', companyEmail);

      const result = await uploadCsvRates(formData);

      setSuccess(`✅ Succès ! ${result.rowCount} tarifs uploadés pour ${result.companyName}`);
      setCompanyName('');
      setCompanyEmail('');
      setFile(null);

      // Reset file input
      const fileInput = document.getElementById('file-input') as HTMLInputElement;
      if (fileInput) {
        fileInput.value = '';
      }

      // Refresh page after 2 seconds
      setTimeout(() => {
        router.refresh();
      }, 2000);
    } catch (err: any) {
      setError(err?.message || "Erreur lors de l'upload du fichier CSV");
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setCompanyName('');
    setCompanyEmail('');
    setFile(null);
    setError(null);
    setSuccess(null);

    const fileInput = document.getElementById('file-input') as HTMLInputElement;
    if (fileInput) {
      fileInput.value = '';
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Upload className="h-5 w-5" />
          Upload tarifs CSV
        </CardTitle>
        <CardDescription>
          Uploadez un fichier CSV contenant les tarifs de transport maritime pour une compagnie.
          Taille maximale : 10 MB. Format requis : .csv
        </CardDescription>
      </CardHeader>

      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Company Name */}
          <div className="space-y-2">
            <Label htmlFor="company-name">
              Nom de la compagnie <span className="text-red-500">*</span>
            </Label>
            <Input
              id="company-name"
              value={companyName}
              onChange={e => setCompanyName(e.target.value)}
              placeholder="Ex: SSC Consolidation"
              required
              disabled={loading}
            />
            <p className="text-xs text-muted-foreground">
              Nom exact de la compagnie maritime (doit correspondre aux données CSV)
            </p>
          </div>

          {/* Company Email */}
          <div className="space-y-2">
            <Label htmlFor="company-email">
              Email de la compagnie <span className="text-red-500">*</span>
            </Label>
            <Input
              id="company-email"
              type="email"
              value={companyEmail}
              onChange={e => setCompanyEmail(e.target.value)}
              placeholder="Ex: bookings@sscconsolidation.com"
              required
              disabled={loading}
            />
            <p className="text-xs text-muted-foreground">
              Email pour les demandes de réservation auprès de cette compagnie
            </p>
          </div>

          {/* File Input */}
          <div className="space-y-2">
            <Label htmlFor="file-input">
              Fichier CSV <span className="text-red-500">*</span>
            </Label>
            <Input
              id="file-input"
              type="file"
              accept=".csv"
              onChange={handleFileChange}
              required
              disabled={loading}
            />
            {file && (
              <p className="text-sm text-muted-foreground">
                Fichier sélectionné: <strong>{file.name}</strong> ({(file.size / 1024).toFixed(2)}{' '}
                KB)
              </p>
            )}
          </div>

          {/* CSV Format Info */}
          <Alert>
            <AlertTitle>Format CSV requis</AlertTitle>
            <AlertDescription className="text-xs space-y-1">
              <p>Le fichier CSV doit contenir les colonnes suivantes :</p>
              <ul className="list-disc list-inside mt-2">
                <li>companyName, origin, destination, containerType</li>
                <li>minVolumeCBM, maxVolumeCBM, minWeightKG, maxWeightKG</li>
                <li>palletCount, pricePerCBM, pricePerKG</li>
                <li>basePriceUSD, basePriceEUR, currency</li>
                <li>hasSurcharges, surchargeBAF, surchargeCAF</li>
                <li>transitDays, validFrom, validUntil</li>
              </ul>
            </AlertDescription>
          </Alert>

          {/* Error Alert */}
          {error && (
            <Alert variant="destructive">
              <XCircle className="h-4 w-4" />
              <AlertTitle>Erreur</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {/* Success Alert */}
          {success && (
            <Alert className="border-green-500 text-green-600">
              <CheckCircle className="h-4 w-4" />
              <AlertTitle>Succès</AlertTitle>
              <AlertDescription>{success}</AlertDescription>
            </Alert>
          )}

          {/* Actions */}
          <div className="flex gap-2">
            <Button type="submit" disabled={loading || !file || !companyName || !companyEmail}>
              {loading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Upload en cours...
                </>
              ) : (
                <>
                  <Upload className="mr-2 h-4 w-4" />
                  Upload CSV
                </>
              )}
            </Button>
            <Button type="button" variant="outline" onClick={handleReset} disabled={loading}>
              Réinitialiser
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
