'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Alert,
  AlertContent,
  AlertDescription,
  AlertIcon,
  AlertTitle,
} from '@/components/ui/alert';
import { Info, Upload } from 'lucide-react';
import useAdminBulkUploadPhones, {
  BulkUploadResult,
} from '../../hooks/useAdminBulkUploadPhones';

// Derive the backend base URL for static assets by stripping the trailing
// `/api` from the configured proxy URL (mirrors network/axios.ts usage).
const backendBaseUrl = (
  process.env.NEXT_PUBLIC_FRONTEND_PROXY_URL || ''
).replace(/\/api\/?$/, '');
const templateUrl = `${backendBaseUrl}/excel/InfluencerNumberBulkExcel.xlsx`;

const acceptedColumnShapes = [
  'User-name, Phone, Phone 2',
  'Username, Platform, Country code, Phone number',
  'platform, influencer_id, country_code, phone_number, influencer_username, influencer_avatar_url',
];

export default function UploadPhonesModal() {
  const [open, setOpen] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [result, setResult] = useState<BulkUploadResult | null>(null);

  const { mutate, isPending } = useAdminBulkUploadPhones();

  const handleOpenChange = (isOpen: boolean) => {
    setOpen(isOpen);
    if (!isOpen) {
      setFile(null);
      setResult(null);
    }
  };

  const handleSubmit = () => {
    if (!file) return;
    mutate(file, {
      onSuccess: (data) => {
        setResult(data);
      },
    });
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button variant="outline">
          <Upload className="size-4" />
          Upload sheet
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Upload Influencer Phone Sheet</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <Alert variant="info" appearance="light">
            <AlertIcon>
              <Info />
            </AlertIcon>
            <AlertContent>
              <AlertTitle>Accepted column shapes</AlertTitle>
              <AlertDescription>
                <ul className="list-disc ps-4 space-y-1">
                  {acceptedColumnShapes.map((shape) => (
                    <li key={shape}>{shape}</li>
                  ))}
                </ul>
                <a
                  href={templateUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-2 inline-block font-medium text-primary underline"
                >
                  Download template
                </a>
              </AlertDescription>
            </AlertContent>
          </Alert>

          <div className="space-y-2">
            <label className="text-sm font-medium" htmlFor="phone-sheet-file">
              File (.xlsx, .xls, .csv)
            </label>
            <Input
              id="phone-sheet-file"
              type="file"
              accept=".xlsx,.xls,.csv"
              onChange={(e) => {
                setFile(e.target.files?.[0] ?? null);
                setResult(null);
              }}
            />
          </div>

          {result && (
            <div className="space-y-3 rounded-lg border p-4">
              <div className="flex items-center gap-2">
                <Badge variant="success">Imported: {result.imported}</Badge>
                <Badge variant="warning">Skipped: {result.skipped}</Badge>
              </div>

              {result.errors.length > 0 && (
                <div className="space-y-2">
                  <p className="text-sm font-medium">
                    Errors ({result.errors.length})
                  </p>
                  <div className="max-h-48 overflow-y-auto rounded-md border">
                    {result.errors.map((err, index) => (
                      <div
                        key={`${err.row_number}-${index}`}
                        className="flex gap-2 border-b px-3 py-2 text-sm last:border-b-0"
                      >
                        <span className="font-mono text-muted-foreground">
                          Row {err.row_number}
                        </span>
                        <span>{err.reason}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => handleOpenChange(false)}
            >
              Close
            </Button>
            <Button type="button" onClick={handleSubmit} disabled={!file || isPending}>
              {isPending ? 'Uploading...' : 'Upload'}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
