import { useState, useEffect, useCallback } from 'react';
import { v4 as uuid } from 'uuid';
import { useSearchParams } from 'react-router-dom';
import { Save, FileDown, ArrowLeft, Plus, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/components/ui/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { PdfFormFieldPalette } from './PdfFormFieldPalette';
import { PdfFormFieldEditor } from './PdfFormFieldEditor';
import { PdfFormCanvas } from './PdfFormCanvas';
import { generatePdfForm } from './generatePdfForm';
import type { PdfFormField, PdfFormFieldType, PdfFormTemplate } from './types';
import { DEFAULT_PAGE_SETTINGS, FIELD_DEFAULTS } from './types';

interface Association { id: string; name: string; logo_url?: string | null; }

export function PdfFormTemplateBuilder() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<Association[]>([]);
  const [selectedAssocId, setSelectedAssocId] = useState('');
  const [templates, setTemplates] = useState<any[]>([]);
  const [activeTemplateId, setActiveTemplateId] = useState<string | null>(null);

  // Builder state
  const [name, setName] = useState('Untitled Form');
  const [fields, setFields] = useState<PdfFormField[]>([]);
  const [selectedFieldId, setSelectedFieldId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [view, setView] = useState<'list' | 'builder'>('list');

  // Load associations
  useEffect(() => {
    supabase.from('associations').select('id, name, logo_url').order('name').then(({ data }) => {
      if (data) setAssociations(data);
    });
  }, []);

  // Load templates when association changes
  useEffect(() => {
    if (!selectedAssocId) { setTemplates([]); return; }
    supabase
      .from('pdf_form_templates')
      .select('*')
      .eq('association_id', selectedAssocId)
      .order('updated_at', { ascending: false })
      .then(({ data }) => { if (data) setTemplates(data); });
  }, [selectedAssocId]);

  const addField = useCallback((type: PdfFormFieldType) => {
    const newField: PdfFormField = {
      id: uuid(),
      type,
      label: FIELD_DEFAULTS[type].label || type,
      ...FIELD_DEFAULTS[type],
    };
    setFields((prev) => [...prev, newField]);
    setSelectedFieldId(newField.id);
  }, []);

  const updateField = useCallback((updated: PdfFormField) => {
    setFields((prev) => prev.map((f) => (f.id === updated.id ? updated : f)));
  }, []);

  const deleteField = useCallback((id: string) => {
    setFields((prev) => prev.filter((f) => f.id !== id));
    if (selectedFieldId === id) setSelectedFieldId(null);
  }, [selectedFieldId]);

  const reorderFields = useCallback((from: number, to: number) => {
    setFields((prev) => {
      const arr = [...prev];
      const [moved] = arr.splice(from, 1);
      arr.splice(to, 0, moved);
      return arr;
    });
  }, []);

  const selectedField = fields.find((f) => f.id === selectedFieldId) || null;

  const openTemplate = (tpl: any) => {
    setActiveTemplateId(tpl.id);
    setName(tpl.name);
    setFields((tpl.fields as PdfFormField[]) || []);
    setSelectedFieldId(null);
    setView('builder');
  };

  const startNew = () => {
    setActiveTemplateId(null);
    setName('Untitled Form');
    setFields([]);
    setSelectedFieldId(null);
    setView('builder');
  };

  const handleSave = async () => {
    if (!selectedAssocId) {
      toast({ variant: 'destructive', title: 'Select an association first' });
      return;
    }
    if (!name.trim()) {
      toast({ variant: 'destructive', title: 'Enter a template name' });
      return;
    }
    setSaving(true);
    try {
      const payload = {
        association_id: selectedAssocId,
        name: name.trim(),
        fields: fields as any,
        page_settings: DEFAULT_PAGE_SETTINGS as any,
      };
      if (activeTemplateId) {
        const { error } = await supabase.from('pdf_form_templates').update(payload).eq('id', activeTemplateId);
        if (error) throw error;
      } else {
        const { data, error } = await supabase.from('pdf_form_templates').insert(payload).select('id').single();
        if (error) throw error;
        setActiveTemplateId(data.id);
      }
      toast({ title: 'Template saved' });
      // Refresh list
      const { data } = await supabase.from('pdf_form_templates').select('*').eq('association_id', selectedAssocId).order('updated_at', { ascending: false });
      if (data) setTemplates(data);
    } catch (err: any) {
      toast({ variant: 'destructive', title: 'Save failed', description: err.message });
    } finally {
      setSaving(false);
    }
  };

  const handleExport = async (mode: 'print' | 'fillable') => {
    if (fields.length === 0) {
      toast({ variant: 'destructive', title: 'Add some fields first' });
      return;
    }
    const template: PdfFormTemplate = {
      association_id: selectedAssocId,
      name,
      fields,
      page_settings: DEFAULT_PAGE_SETTINGS,
    };
    // Get association logo
    const assoc = associations.find((a) => a.id === selectedAssocId);
    const logoUrl = assoc?.logo_url || null;
    const doc = await generatePdfForm(template, mode, logoUrl);
    doc.save(`${name.replace(/[^a-z0-9]/gi, '_').toLowerCase() || 'form'}.pdf`);
    toast({ title: `PDF exported (${mode === 'print' ? 'Print-Ready' : 'Fillable'})` });
  };

  const handleDelete = async (id: string) => {
    await supabase.from('pdf_form_templates').delete().eq('id', id);
    setTemplates((prev) => prev.filter((t) => t.id !== id));
    toast({ title: 'Template deleted' });
  };

  // LIST VIEW
  if (view === 'list') {
    return (
      <div className="p-6 max-w-4xl mx-auto w-full">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-lg font-bold text-foreground">PDF Form Creator</h2>
            <p className="text-xs text-muted-foreground mt-0.5">Build printable forms with text lines, signature lines, and checkboxes</p>
          </div>
          <Button size="sm" className="gap-1.5 text-xs" onClick={startNew} disabled={!selectedAssocId}>
            <Plus className="h-3.5 w-3.5" /> New Form Template
          </Button>
        </div>

        <div className="mb-4">
          <Label className="text-[11px] text-muted-foreground">Association</Label>
          <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
            <SelectTrigger className="w-[300px] h-9 text-xs mt-1"><SelectValue placeholder="Select association..." /></SelectTrigger>
            <SelectContent>
              {associations.map((a) => (
                <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {!selectedAssocId ? (
          <div className="text-center py-16 text-muted-foreground text-sm">Select an association to view or create form templates</div>
        ) : templates.length === 0 ? (
          <div className="text-center py-16 text-muted-foreground text-sm">No form templates yet. Click "New Form Template" to get started.</div>
        ) : (
          <div className="space-y-2">
            {templates.map((tpl) => (
              <div key={tpl.id} className="flex items-center justify-between px-4 py-3 border rounded-lg hover:bg-muted/50 transition-colors">
                <div className="cursor-pointer flex-1" onClick={() => openTemplate(tpl)}>
                  <div className="text-sm font-medium text-foreground">{tpl.name}</div>
                  <div className="text-[11px] text-muted-foreground">{((tpl.fields as any[]) || []).length} fields · Updated {new Date(tpl.updated_at).toLocaleDateString()}</div>
                </div>
                <div className="flex items-center gap-1.5">
                  <Button variant="outline" size="sm" className="text-xs h-7" onClick={() => openTemplate(tpl)}>Edit</Button>
                  <Button variant="ghost" size="sm" className="text-xs h-7 text-destructive" onClick={() => handleDelete(tpl.id)}>Delete</Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  // BUILDER VIEW
  return (
    <div className="flex flex-col h-full min-h-0">
      {/* Toolbar */}
      <div className="px-4 py-2.5 border-b bg-card flex items-center gap-3 flex-wrap">
        <Button variant="ghost" size="sm" className="text-xs gap-1 h-8" onClick={() => setView('list')}>
          <ArrowLeft className="h-3.5 w-3.5" /> Back
        </Button>
        <Separator orientation="vertical" className="h-5" />
        <Input
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="h-8 w-[220px] text-xs font-medium"
          placeholder="Form template name..."
        />
        <div className="flex-1" />
        <Button variant="outline" size="sm" className="text-xs h-8 gap-1.5" onClick={handleSave} disabled={saving}>
          {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
          Save
        </Button>
        <Button variant="outline" size="sm" className="text-xs h-8 gap-1.5" onClick={() => handleExport('print')}>
          <FileDown className="h-3.5 w-3.5" /> Export Print PDF
        </Button>
        <Button size="sm" className="text-xs h-8 gap-1.5" onClick={() => handleExport('fillable')}>
          <FileDown className="h-3.5 w-3.5" /> Export Fillable PDF
        </Button>
      </div>

      {/* Body: Palette | Canvas | Properties */}
      <div className="flex flex-1 min-h-0">
        {/* Left: Field Palette */}
        <div className="w-[180px] shrink-0 border-r bg-card p-3 overflow-y-auto">
          <PdfFormFieldPalette onAdd={addField} />
        </div>

        {/* Center: Canvas */}
        <div className="flex-1 min-w-0 bg-muted/30 overflow-hidden flex flex-col">
          <PdfFormCanvas
            fields={fields}
            selectedId={selectedFieldId}
            onSelect={setSelectedFieldId}
            onDelete={deleteField}
            onReorder={reorderFields}
          />
        </div>

        {/* Right: Property Editor */}
        <div className="w-[240px] shrink-0 border-l bg-card p-3 overflow-y-auto">
          {selectedField ? (
            <PdfFormFieldEditor field={selectedField} onChange={updateField} />
          ) : (
            <div className="text-xs text-muted-foreground text-center pt-8">
              Select a field to edit its properties
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
