import { useState, useEffect, useMemo, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { notifyStaffOfArcSubmission } from "@/lib/arcSubmissionEmail";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useDropzone } from "react-dropzone";
import {
  Plus, FileText, Clock, CheckCircle2, XCircle, AlertCircle,
  RefreshCw, UploadCloud, X, File, Gavel,
} from "lucide-react";
import { format } from "date-fns";

const STATUS_CONFIG: Record<string, { label: string; cls: string; icon: React.ElementType }> = {
  submitted:        { label: "Submitted",        cls: "bg-blue-100 text-blue-700 border-blue-200",           icon: FileText },
  pending:          { label: "Pending",           cls: "bg-blue-100 text-blue-700 border-blue-200",           icon: FileText },
  under_review:     { label: "Under Review",     cls: "bg-amber-100 text-amber-700 border-amber-200",       icon: Clock },
  "in-review":      { label: "In Review",        cls: "bg-amber-100 text-amber-700 border-amber-200",       icon: AlertCircle },
  approved:         { label: "Approved",          cls: "bg-emerald-100 text-emerald-700 border-emerald-200", icon: CheckCircle2 },
  denied:           { label: "Denied",            cls: "bg-red-100 text-red-700 border-red-200",             icon: XCircle },
  withdrawn:        { label: "Withdrawn",         cls: "bg-muted text-muted-foreground border-border",       icon: XCircle },
};

const getStatus = (s: string | null) => STATUS_CONFIG[s || "pending"] || STATUS_CONFIG.pending;

export default function HomeownerARCPage() {
  const { currentOwner, association, unit, loading: ctxLoading } = useHomeowner();
  const { toast } = useToast();
  const [applications, setApplications] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [arcFiles, setArcFiles] = useState<File[]>([]);
  const [arcUploading, setArcUploading] = useState(false);

  const fetchApps = useCallback(async () => {
    if (!currentOwner) return;
    setLoading(true);
    const { data } = await supabase
      .from("arc_applications")
      .select("*")
      .eq("owner_id", currentOwner.id)
      .order("created_at", { ascending: false });
    setApplications(data || []);
    setLoading(false);
  }, [currentOwner]);

  useEffect(() => {
    if (currentOwner) fetchApps();
    else { setApplications([]); setLoading(false); }
  }, [currentOwner, fetchApps]);

  // Dropzone
  const onArcDrop = useCallback((acceptedFiles: File[]) => {
    const maxSize = 20 * 1024 * 1024;
    const valid = acceptedFiles.filter(f => f.size <= maxSize);
    setArcFiles(prev => [...prev, ...valid].slice(0, 15));
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop: onArcDrop,
    maxSize: 20 * 1024 * 1024,
    maxFiles: 15,
  });

  // Submit
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!currentOwner || !association) {
      toast({ title: "Error", description: "Owner record not found", variant: "destructive" });
      return;
    }
    setArcUploading(true);
    const form = new FormData(e.currentTarget);

    try {
      const { data: inserted, error } = await supabase.from("arc_applications").insert({
        association_id: currentOwner.association_id,
        owner_id: currentOwner.id,
        unit_id: currentOwner.unit_id,
        title: form.get("title") as string,
        description: (form.get("description") as string) || null,
        project_type: (form.get("project_type") as string) || null,
        status: "pending",
        submitted_date: new Date().toISOString().split("T")[0],
      }).select("id").single();

      if (error) throw error;

      if (arcFiles.length > 0 && inserted) {
        const addressLabel = propertyDisplay || "Unknown Address";
        for (const file of arcFiles) {
          const storagePath = `${currentOwner.association_id}/${inserted.id}/${Date.now()}-${file.name}`;
          const { error: upErr } = await supabase.storage.from("arc-files").upload(storagePath, file, { contentType: file.type });
          if (upErr) continue;
          const { data: urlData } = supabase.storage.from("arc-files").getPublicUrl(storagePath);
          await supabase.from("documents").insert({
            title: `${addressLabel} - ${(form.get("title") as string) || "ARC Application"} - ${file.name}`,
            file_name: file.name,
            file_url: urlData.publicUrl,
            file_size: file.size,
            category: "ARC Applications",
            association_id: currentOwner.association_id,
            visibility: [],
            is_public: false,
          });
        }
      }

      toast({ title: "Application submitted successfully" });
      setDialogOpen(false);
      setArcFiles([]);

      // Fire-and-forget staff notification email
      if (inserted?.id) {
        notifyStaffOfArcSubmission({
          applicationId: inserted.id,
          applicationTitle: (form.get("title") as string) || "Architectural review request",
          homeownerName: ownerDisplayName,
          associationId: currentOwner.association_id,
          associationName: association?.name,
          propertyAddress: propertyDisplay,
          projectType: (form.get("project_type") as string) || null,
          description: (form.get("description") as string) || null,
          fileCount: arcFiles.length,
        });
      }

      fetchApps();
    } catch (err: any) {
      toast({ title: "Error", description: err.message, variant: "destructive" });
    } finally {
      setArcUploading(false);
    }
  };

  const ownerDisplayName = currentOwner
    ? `${currentOwner.first_name} ${currentOwner.last_name}`
    : "";
  const propertyDisplay = unit?.address || unit?.unit_number || currentOwner?.property_address || "";

  if (ctxLoading || loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10">
            <Gavel className="h-5 w-5 text-primary" />
          </div>
          <div>
            <h1 className="text-[22px] font-bold tracking-tight text-foreground">ARC Applications</h1>
            <p className="text-[13px] text-muted-foreground">Submit and track architectural review requests.</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" className="gap-1.5 h-8 text-[12px]" onClick={fetchApps}>
            <RefreshCw className="h-3.5 w-3.5" /> Refresh
          </Button>
          <Button size="sm" className="gap-1.5 h-8 text-[12px]" onClick={() => setDialogOpen(true)} disabled={!currentOwner}>
            <Plus className="h-3.5 w-3.5" /> New Application
          </Button>
        </div>
      </div>

      {!currentOwner && (
        <Card>
          <CardContent className="text-center text-muted-foreground">
            Your account is not linked to an owner record. Please contact management.
          </CardContent>
        </Card>
      )}

      {currentOwner && (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Project</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Submitted</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {applications.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-12 text-muted-foreground">
                      No applications submitted yet. Click "New Application" to get started.
                    </TableCell>
                  </TableRow>
                ) : (
                  applications.map((app) => {
                    const st = getStatus(app.status);
                    const Icon = st.icon;
                    return (
                      <TableRow key={app.id}>
                        <TableCell>
                          <p className="font-medium">{app.title}</p>
                          {app.description && (
                            <p className="text-xs text-muted-foreground line-clamp-1">{app.description}</p>
                          )}
                        </TableCell>
                        <TableCell className="text-sm">{app.project_type || "—"}</TableCell>
                        <TableCell>
                          <Badge variant="outline" className={`gap-1 ${st.cls}`}>
                            <Icon className="h-3 w-3" /> {st.label}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-sm">
                          {app.submitted_date ? format(new Date(app.submitted_date), "MMM d, yyyy") : "—"}
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* New Application Dialog — matches admin form */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[540px] max-h-[90vh] overflow-y-auto">
          <DialogHeader><DialogTitle>Submit ARC Application</DialogTitle></DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Auto-populated ownership info */}
            <div className="space-y-2">
              <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Ownership Account</Label>
              <Input
                value={`${propertyDisplay}${propertyDisplay && ownerDisplayName ? " — " : ""}${ownerDisplayName}`}
                readOnly
                className="bg-muted/50 cursor-default"
              />
            </div>

            {association && (
              <div className="space-y-2">
                <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Association</Label>
                <Input value={association.name} readOnly className="bg-muted/50 cursor-default" />
              </div>
            )}

            {/* Date & Time */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Date of Request *</Label>
                <Input name="request_date" type="date" defaultValue={format(new Date(), "yyyy-MM-dd")} required />
              </div>
              <div className="space-y-2">
                <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Time *</Label>
                <Input name="request_time" type="time" defaultValue={format(new Date(), "HH:mm")} required />
                <p className="text-[11px] text-muted-foreground">Eastern Time (US and Canada)</p>
              </div>
            </div>

            {/* File Upload */}
            <div className="space-y-2">
              <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">File Upload (Optional)</Label>
              <p className="text-xs text-muted-foreground">Each file must be 20 MB or less. Attach up to 15 files.</p>
              <div
                {...getRootProps()}
                className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
                  isDragActive ? "border-primary bg-primary/5" : "border-border hover:border-primary/50"
                }`}
              >
                <input {...getInputProps()} />
                <div className="flex flex-col items-center gap-2">
                  <UploadCloud className="h-8 w-8 text-muted-foreground/40" />
                  <p className="text-sm text-muted-foreground">
                    Drag & drop files here or <span className="text-primary font-medium cursor-pointer">browse</span>
                  </p>
                </div>
              </div>
              {arcFiles.length > 0 && (
                <div className="space-y-1 mt-2 max-h-[120px] overflow-y-auto">
                  {arcFiles.map((f, i) => (
                    <div key={i} className="flex items-center justify-between text-sm py-1.5 px-2 rounded border bg-muted/30">
                      <div className="flex items-center gap-2 min-w-0">
                        <File className="h-4 w-4 text-muted-foreground shrink-0" />
                        <span className="truncate text-xs">{f.name}</span>
                      </div>
                      <Button type="button" variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => setArcFiles(prev => prev.filter((_, idx) => idx !== i))}>
                        <X className="h-3 w-3" />
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Project Name */}
            <div className="space-y-2">
              <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Project Name *</Label>
              <Input name="title" required maxLength={30} placeholder="e.g. Fence Replacement" />
              <p className="text-[11px] text-muted-foreground text-right">30 character limit</p>
            </div>

            {/* Description */}
            <div className="space-y-2">
              <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Description</Label>
              <Textarea name="description" placeholder="Describe the project details..." />
            </div>

            {/* Project Type */}
            <div className="space-y-2">
              <Label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Project Type</Label>
              <Input name="project_type" placeholder="e.g. Fence, Roof, Paint" />
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
              <Button type="submit" disabled={arcUploading}>
                {arcUploading ? "Submitting..." : "Submit Application"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
