"use client";

import { useState } from "react";

import { Search } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
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 {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import { ARCHETYPES } from "@/data/archetypes";
import { DEMO_LEADS } from "@/data/leads";
import type { Lead, LeadStatus } from "@/types/novalife";

const PIPELINE_STAGES: { status: LeadStatus; label: string; color: string }[] = [
  { status: "new", label: "New", color: "bg-blue-50 border-blue-200" },
  { status: "contacted", label: "Contacted", color: "bg-amber-50 border-amber-200" },
  { status: "qualified", label: "Qualified", color: "bg-violet-50 border-violet-200" },
  { status: "converted", label: "Converted", color: "bg-green-50 border-green-200" },
  { status: "lost", label: "Lost", color: "bg-gray-50 border-gray-200" },
];

const SOURCE_LABELS: Record<string, string> = {
  quiz_started: "Quiz",
  signup: "Signup",
  organic: "Organic",
  instagram: "Instagram",
  google: "Google",
};

export default function CRMPage() {
  const [search, setSearch] = useState("");
  const [selectedLead, setSelectedLead] = useState<Lead | null>(null);
  const [note, setNote] = useState("");

  const filtered = DEMO_LEADS.filter(
    (l) =>
      !search ||
      l.email.toLowerCase().includes(search.toLowerCase()) ||
      (l.firstName?.toLowerCase() ?? "").includes(search.toLowerCase()),
  );

  const leadsByStatus = (status: LeadStatus) => filtered.filter((l) => l.status === status);

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">CRM & Leads</h1>
          <p className="text-sm text-gray-500 mt-1">Manage your lead pipeline and track conversions.</p>
        </div>
        <Button size="sm" className="bg-teal-600 hover:bg-teal-700 text-white" onClick={() => toast.info("CSV export triggered (PoC simulation)")}>Export CSV</Button>
      </div>

      {/* Search */}
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
        <Input placeholder="Search leads..." className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      {/* Pipeline Summary */}
      <div className="grid gap-3 sm:grid-cols-5">
        {PIPELINE_STAGES.map((stage) => (
          <div key={stage.status} className={`rounded-xl border p-4 text-center ${stage.color}`}>
            <p className="text-2xl font-bold text-gray-900">{DEMO_LEADS.filter((l) => l.status === stage.status).length}</p>
            <p className="text-xs font-medium text-gray-600 mt-0.5">{stage.label}</p>
          </div>
        ))}
      </div>

      {/* Kanban Board */}
      <div className="grid gap-4 md:grid-cols-5">
        {PIPELINE_STAGES.map((stage) => {
          const leads = leadsByStatus(stage.status);
          return (
            <div key={stage.status} className="flex flex-col gap-2">
              <div className={`flex items-center justify-between rounded-t-lg border-b-2 px-3 py-2 ${stage.color}`}>
                <span className="text-xs font-bold uppercase tracking-wide text-gray-700">{stage.label}</span>
                <Badge variant="outline" className="text-xs">{leads.length}</Badge>
              </div>
              <div className="space-y-2">
                {leads.map((lead) => {
                  const archetype = lead.archetypeId ? ARCHETYPES.find((a) => a.id === lead.archetypeId) : null;
                  return (
                    <Card
                      key={lead.id}
                      className="cursor-pointer border-gray-100 hover:shadow-sm transition-shadow"
                      onClick={() => setSelectedLead(lead)}
                    >
                      <CardContent className="p-3">
                        <p className="font-medium text-gray-900 text-sm truncate">
                          {lead.firstName ? `${lead.firstName} ${lead.lastName ?? ""}` : lead.email}
                        </p>
                        <p className="text-xs text-gray-400 truncate mt-0.5">{lead.email}</p>
                        <div className="flex flex-wrap gap-1 mt-2">
                          <span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600">
                            {SOURCE_LABELS[lead.source] ?? lead.source}
                          </span>
                          {archetype && (
                            <span
                              className="rounded-full px-2 py-0.5 text-xs"
                              style={{ backgroundColor: archetype.bgColor, color: archetype.color }}
                            >
                              {archetype.name.split(" ").slice(-1)[0]}
                            </span>
                          )}
                        </div>
                        <p className="text-xs text-gray-400 mt-1.5">{new Date(lead.lastActivity).toLocaleDateString()}</p>
                      </CardContent>
                    </Card>
                  );
                })}
                {leads.length === 0 && (
                  <p className="text-center text-xs text-gray-400 py-4">No leads</p>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Lead Detail Sheet */}
      <Sheet open={!!selectedLead} onOpenChange={() => setSelectedLead(null)}>
        <SheetContent className="w-full max-w-md overflow-y-auto">
          <SheetHeader>
            <SheetTitle>Lead Details</SheetTitle>
          </SheetHeader>
          {selectedLead && (
            <div className="mt-4 space-y-5">
              <div>
                <p className="text-lg font-bold text-gray-900">
                  {selectedLead.firstName} {selectedLead.lastName}
                </p>
                <p className="text-sm text-gray-500">{selectedLead.email}</p>
              </div>
              <Separator />
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div><Label className="text-xs text-gray-400">Source</Label><p>{SOURCE_LABELS[selectedLead.source]}</p></div>
                <div><Label className="text-xs text-gray-400">Status</Label><p className="capitalize">{selectedLead.status}</p></div>
                <div><Label className="text-xs text-gray-400">Created</Label><p>{new Date(selectedLead.createdAt).toLocaleDateString()}</p></div>
                <div><Label className="text-xs text-gray-400">Last Activity</Label><p>{new Date(selectedLead.lastActivity).toLocaleDateString()}</p></div>
              </div>
              {selectedLead.tags.length > 0 && (
                <div>
                  <Label className="text-xs text-gray-400">Tags</Label>
                  <div className="flex flex-wrap gap-1.5 mt-1">
                    {selectedLead.tags.map((tag) => (
                      <Badge key={tag} variant="outline" className="text-xs">{tag}</Badge>
                    ))}
                  </div>
                </div>
              )}
              {selectedLead.notes && (
                <div>
                  <Label className="text-xs text-gray-400">Notes</Label>
                  <p className="text-sm text-gray-600 mt-1 leading-relaxed">{selectedLead.notes}</p>
                </div>
              )}
              <Separator />
              <div className="space-y-2">
                <Label className="text-xs text-gray-500">Update Status</Label>
                <Select defaultValue={selectedLead.status} onValueChange={() => toast.success("Status updated (PoC simulation)")}>
                  <SelectTrigger className="h-8"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {PIPELINE_STAGES.map((s) => (
                      <SelectItem key={s.status} value={s.status}>{s.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label className="text-xs text-gray-500">Add Note</Label>
                <Textarea placeholder="Enter a note..." rows={3} value={note} onChange={(e) => setNote(e.target.value)} />
                <Button size="sm" className="w-full bg-teal-600 hover:bg-teal-700 text-white" onClick={() => { toast.success("Note saved (PoC simulation)"); setNote(""); }}>
                  Save Note
                </Button>
              </div>
            </div>
          )}
        </SheetContent>
      </Sheet>
    </div>
  );
}
