import { useState } from "react";
import { Alert, Button, Group, Modal, Stack, Table, Text, FileInput, Badge } from "@mantine/core";
import { Upload, Download, AlertCircle, CheckCircle, AlertTriangle } from "lucide-react";
import { useMutation } from "@tanstack/react-query";

import { client } from "@/utils/api";
import { generateTruckAssignmentTemplate, parseTruckAssignmentFile } from "@/utils/truck-assignment-template";

interface BulkTruckUploadModalProps {
  opened: boolean;
  onClose: () => void;
  bookingId: string;
  onSuccess?: () => void;
}

export function BulkTruckUploadModal({
  opened,
  onClose,
  bookingId,
  onSuccess,
}: BulkTruckUploadModalProps) {
  const [file, setFile] = useState<File | null>(null);
  const [parsed, setParsed] = useState<
    Array<{
      truckPlateNumber: string;
      driverName: string;
      truckType: string;
      containerNumbers?: string[];
    }>
  >([]);
  const [parseError, setParseError] = useState<string | null>(null);

  const uploadMutation = useMutation({
    mutationFn: async () => {
      const { data } = await client.post(`/bookings/${bookingId}/customer-trucks/bulk`, {
        trucks: parsed,
      });
      return data;
    },
    onSuccess: () => {
      onSuccess?.();
      setFile(null);
      setParsed([]);
      onClose();
    },
  });

  const handleFileSelect = async (selectedFile: File | null) => {
    if (!selectedFile) {
      setFile(null);
      setParsed([]);
      setParseError(null);
      return;
    }

    try {
      setParseError(null);
      const trucks = await parseTruckAssignmentFile(selectedFile);
      setFile(selectedFile);
      setParsed(trucks);
    } catch (err: any) {
      setParseError(err.message || "Failed to parse Excel file");
      setFile(null);
      setParsed([]);
    }
  };

  const handleDownloadTemplate = () => {
    generateTruckAssignmentTemplate("truck-assignments.xlsx");
  };

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title="Bulk Upload Truck Assignments"
      size="lg"
      centered
    >
      <Stack gap="lg">
        <Alert icon={<AlertCircle size={16} />} color="blue">
          Download template, fill with truck data, upload Excel file to bulk-create truck assignments.
        </Alert>

        <Group>
          <Button
            leftSection={<Download size={16} />}
            variant="light"
            onClick={handleDownloadTemplate}
          >
            Download Template
          </Button>
        </Group>

        <FileInput
          label="Select Excel File"
          placeholder="Choose .xlsx file"
          accept=".xlsx,.xls"
          value={file}
          onChange={handleFileSelect}
          leftSection={<Upload size={14} />}
        />

        {parseError && (
          <Alert icon={<AlertTriangle size={16} />} color="red" title="Parse Error">
            {parseError}
          </Alert>
        )}

        {parsed.length > 0 && (
          <>
            <div>
              <Text fw={600} mb="xs">
                Preview ({parsed.length} trucks)
              </Text>
              <Table striped highlightOnHover verticalSpacing="xs">
                <Table.Thead>
                  <Table.Tr>
                    <Table.Th>Plate Number</Table.Th>
                    <Table.Th>Driver Name</Table.Th>
                    <Table.Th>Truck Type</Table.Th>
                    <Table.Th>Containers</Table.Th>
                  </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                  {parsed.map((truck, idx) => (
                    <Table.Tr key={idx}>
                      <Table.Td>
                        <Text size="sm">{truck.truckPlateNumber}</Text>
                      </Table.Td>
                      <Table.Td>
                        <Text size="sm">{truck.driverName}</Text>
                      </Table.Td>
                      <Table.Td>
                        <Text size="sm">{truck.truckType}</Text>
                      </Table.Td>
                      <Table.Td>
                        {truck.containerNumbers?.length ? (
                          <Group gap="xs">
                            {truck.containerNumbers.map((c) => (
                              <Badge key={c} size="sm">
                                {c}
                              </Badge>
                            ))}
                          </Group>
                        ) : (
                          <Text size="sm" c="dimmed">
                            —
                          </Text>
                        )}
                      </Table.Td>
                    </Table.Tr>
                  ))}
                </Table.Tbody>
              </Table>
            </div>

            <Group justify="space-between">
              <Text size="sm" c="dimmed">
                Ready to upload {parsed.length} truck(s)
              </Text>
              <Button
                loading={uploadMutation.isPending}
                onClick={() => uploadMutation.mutate()}
                leftSection={<CheckCircle size={16} />}
              >
                Upload Trucks
              </Button>
            </Group>
          </>
        )}

        {uploadMutation.isError && (
          <Alert icon={<AlertTriangle size={16} />} color="red">
            {uploadMutation.error instanceof Error
              ? uploadMutation.error.message
              : "Upload failed"}
          </Alert>
        )}
      </Stack>
    </Modal>
  );
}
