import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CheckCircle2,
  FileCheck,
  Loader2,
  UploadCloud,
  XCircle,
} from "lucide-react";
import { api } from "@/services/api";
import { companiesService } from "@/services/companies.service";
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Button,
  SmartFileInput,
} from "@edr/ui-common";
import type { ProfileResponse } from "@/types/profile";

export default function TabDocuments({ profile }: { profile: ProfileResponse }) {
  const queryClient = useQueryClient();
  const [documentFiles, setDocumentFiles] = useState<Record<string, File | File[] | null>>({});

  const docSettingQuery = useQuery(
    api.fileUploadSettings.getByCode.queryOptions({
      input: { code: "customer_documents" },
    }),
  );

  const docUploadMutation = useMutation({
    mutationFn: (files: Record<string, File | File[] | null>) =>
      companiesService.uploadDocuments(profile.companyId, files),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: api.companies.getProfile.queryKey() });
    },
  });

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FileCheck className="size-5 text-primary" />
          Documents
        </CardTitle>
        <CardDescription>
          Upload and manage required business documents
        </CardDescription>
      </CardHeader>
      <CardContent>
        {docSettingQuery.isLoading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="size-6 animate-spin text-muted-foreground" />
          </div>
        ) : !docSettingQuery.data ? (
          <p className="text-sm text-muted-foreground text-center py-4">
            No document requirements configured for your account.
          </p>
        ) : (
          <SmartFileInput
            file={docSettingQuery.data}
            value={documentFiles}
            onChange={setDocumentFiles}
          />
        )}

        {docSettingQuery.data && (
          <div className="flex items-center justify-between pt-4">
            <div className="flex items-center gap-2">
              {docUploadMutation.isSuccess && (
                <span className="flex items-center gap-1.5 text-sm font-medium text-emerald-600">
                  <CheckCircle2 className="size-4" />
                  Documents uploaded successfully
                </span>
              )}
              {docUploadMutation.isError && (
                <span className="flex items-center gap-1.5 text-sm font-medium text-red-600">
                  <XCircle className="size-4" />
                  Upload failed
                </span>
              )}
            </div>
            <Button
              type="button"
              onClick={() => docUploadMutation.mutate(documentFiles)}
              disabled={docUploadMutation.isPending}
            >
              {docUploadMutation.isPending ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  Uploading...
                </>
              ) : (
                <>
                  <UploadCloud className="size-4" />
                  Upload Documents
                </>
              )}
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
