'use client';

import { useMemo, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { apiFetch } from '@/lib/api/client';

interface EoiPrerequisites {
  hasName: boolean;
  hasYacht: boolean;
  hasBerth: boolean;
}

interface EoiGenerateDialogProps {
  interestId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  prerequisites: EoiPrerequisites;
}

const PREREQUISITE_LABELS: { key: keyof EoiPrerequisites; label: string }[] = [
  { key: 'hasName', label: 'Client has full name' },
  { key: 'hasYacht', label: 'Yacht linked to interest' },
  { key: 'hasBerth', label: 'Berth linked to interest' },
];

const DOCUMENSO_TEMPLATE_VALUE = 'documenso-template';

interface InAppTemplate {
  id: string;
  name: string;
  description?: string | null;
  templateType: string;
}

interface ListResponse {
  data: InAppTemplate[];
}

export function EoiGenerateDialog({
  interestId,
  open,
  onOpenChange,
  prerequisites,
}: EoiGenerateDialogProps) {
  const queryClient = useQueryClient();
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedTemplate, setSelectedTemplate] = useState<string>(DOCUMENSO_TEMPLATE_VALUE);

  const allMet = Object.values(prerequisites).every(Boolean);

  // Load in-app EOI templates so the operator can pick one as an alternative
  // to the Documenso external-signing flow.
  const { data: templatesRes } = useQuery<ListResponse>({
    queryKey: ['document-templates', { templateType: 'eoi', isActive: true }],
    queryFn: () =>
      apiFetch<ListResponse>('/api/v1/document-templates?templateType=eoi&isActive=true'),
    enabled: open,
  });

  const inAppTemplates = useMemo(() => templatesRes?.data ?? [], [templatesRes]);

  const handleGenerate = async () => {
    if (!allMet) return;

    setIsGenerating(true);
    setError(null);

    try {
      const isDocumensoPath = selectedTemplate === DOCUMENSO_TEMPLATE_VALUE;
      const url = `/api/v1/document-templates/${encodeURIComponent(selectedTemplate)}/generate-and-sign`;
      await apiFetch(url, {
        method: 'POST',
        body: {
          interestId,
          pathway: isDocumensoPath ? 'documenso-template' : 'inapp',
          // Signers are derived server-side from EOI context for both pathways
          // when the template type is EOI, so the dialog doesn't collect them.
          signers: [],
        },
      });

      queryClient.invalidateQueries({ queryKey: ['documents', { interestId }] });
      onOpenChange(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to generate EOI');
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Generate Expression of Interest</DialogTitle>
          <DialogDescription>
            Pick how to render the EOI. Documenso is the primary path; in-app templates use the same
            source PDF but render and store the PDF locally before sending for signing.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="space-y-2">
            <Label htmlFor="eoi-template">Template</Label>
            <Select value={selectedTemplate} onValueChange={setSelectedTemplate}>
              <SelectTrigger id="eoi-template">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={DOCUMENSO_TEMPLATE_VALUE}>
                  Documenso Standard EOI (recommended)
                </SelectItem>
                {inAppTemplates.map((t) => (
                  <SelectItem key={t.id} value={t.id}>
                    {t.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <p className="text-xs font-medium text-muted-foreground">Prerequisites</p>
            {PREREQUISITE_LABELS.map(({ key, label }) => (
              <div key={key} className="flex items-center gap-3">
                <span
                  className={`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${
                    prerequisites[key] ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                  }`}
                >
                  {prerequisites[key] ? '✓' : '✗'}
                </span>
                <span className={prerequisites[key] ? 'text-foreground' : 'text-muted-foreground'}>
                  {label}
                </span>
              </div>
            ))}
          </div>
        </div>

        {error && <p className="text-sm text-destructive">{error}</p>}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={handleGenerate} disabled={!allMet || isGenerating}>
            {isGenerating ? 'Generating…' : 'Generate EOI'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
