"use client";

import { useActionState, useEffect, useState, useTransition } from "react";
import {
  Calendar, CheckCircle2, ChevronDown, Loader2, Mail, MessageSquarePlus,
  Phone, TrendingUp, UserCheck, X,
} from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
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 {
  Sheet, SheetContent, SheetHeader, SheetTitle,
} from "@/components/ui/sheet";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { formatCurrency, formatDateTime } from "@/lib/format";
import {
  addLeadActivityAction,
  scheduleFollowUpAction,
} from "@/lib/appwrite/lead-activity-actions";
import { convertLeadToCustomerAction } from "@/lib/appwrite/lead-actions";

import {
  ACTIVITY_TYPE_CONFIG,
  LEAD_SOURCE_LABEL,
  LEAD_STATUS_CONFIG,
  type ActivityRow,
  type LeadActivityType,
  type LeadRow,
} from "./types";

type Props = {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  lead: LeadRow | null;
  activities: ActivityRow[];
  onEdit: (lead: LeadRow) => void;
};

const ACTIVITY_TYPES: LeadActivityType[] = ["note", "call", "meeting", "email"];

export function LeadDetailSheet({ open, onOpenChange, lead, activities, onEdit }: Props) {
  const [activityState, activityAction, activityPending] = useActionState(
    addLeadActivityAction, { ok: false },
  );
  const [followUpState, followUpAction, followUpPending] = useActionState(
    scheduleFollowUpAction, { ok: false },
  );
  const [convertBusy, startConvert] = useTransition();
  const [tab, setTab] = useState<"activities" | "followup">("activities");
  const [activityType, setActivityType] = useState<LeadActivityType>("note");

  useEffect(() => {
    if (activityState.ok) toast.success("Aktivite kaydedildi.");
    else if (activityState.error) toast.error(activityState.error);
  }, [activityState]);

  useEffect(() => {
    if (followUpState.ok) { toast.success("Takip takvime eklendi."); setTab("activities"); }
    else if (followUpState.error) toast.error(followUpState.error);
  }, [followUpState]);

  const handleConvert = () => {
    if (!lead) return;
    startConvert(async () => {
      const fd = new FormData();
      fd.set("leadId", lead.id);
      const result = await convertLeadToCustomerAction(fd);
      if (result.ok) {
        toast.success("Müşteriye dönüştürüldü.");
        onOpenChange(false);
      } else {
        toast.error(result.error ?? "Dönüştürme başarısız.");
      }
    });
  };

  if (!lead) return null;
  const cfg = LEAD_STATUS_CONFIG[lead.status];

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex w-full flex-col gap-0 overflow-hidden p-0 sm:max-w-lg">
        <SheetHeader className="border-b px-6 py-4">
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0">
              <SheetTitle className="truncate">{lead.name}</SheetTitle>
              {lead.contactName && (
                <p className="text-muted-foreground mt-0.5 text-sm">{lead.contactName}</p>
              )}
            </div>
            <Badge variant="outline" className={cn("shrink-0 text-xs", cfg.color, cfg.bg, cfg.border)}>
              {cfg.label}
            </Badge>
          </div>
        </SheetHeader>

        <div className="flex flex-1 flex-col overflow-hidden">
          {/* Info strip */}
          <div className="bg-muted/30 flex flex-wrap gap-3 border-b px-6 py-3 text-xs">
            {lead.phone && (
              <a href={`tel:${lead.phone}`} className="text-muted-foreground hover:text-foreground flex items-center gap-1.5">
                <Phone className="size-3.5" /> {lead.phone}
              </a>
            )}
            {lead.email && (
              <a href={`mailto:${lead.email}`} className="text-muted-foreground hover:text-foreground flex items-center gap-1.5">
                <Mail className="size-3.5" /> {lead.email}
              </a>
            )}
            {lead.estimatedValue != null && lead.estimatedValue > 0 && (
              <span className="flex items-center gap-1.5 font-medium">
                <TrendingUp className="size-3.5" />
                {formatCurrency(lead.estimatedValue, lead.currency)}
              </span>
            )}
            <span className="text-muted-foreground">{LEAD_SOURCE_LABEL[lead.source]}</span>
          </div>

          {/* Tab bar */}
          <div className="flex border-b">
            {(["activities", "followup"] as const).map((t) => (
              <button
                key={t}
                type="button"
                onClick={() => setTab(t)}
                className={cn(
                  "flex-1 px-4 py-2.5 text-sm font-medium transition-colors",
                  tab === t
                    ? "border-b-2 border-primary text-foreground"
                    : "text-muted-foreground hover:text-foreground",
                )}
              >
                {t === "activities" ? "Aktiviteler" : "Takip Planla"}
              </button>
            ))}
          </div>

          <div className="flex-1 overflow-y-auto">
            {tab === "activities" && (
              <div className="space-y-4 px-6 py-4">
                {/* Add activity form */}
                <form action={activityAction} className="space-y-3 rounded-lg border bg-muted/20 p-3">
                  <input type="hidden" name="leadId" value={lead.id} />
                  <div className="flex items-center gap-2">
                    <Select
                      name="type"
                      value={activityType}
                      onValueChange={(v) => setActivityType(v as LeadActivityType)}
                    >
                      <SelectTrigger className="h-8 w-[140px] text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {ACTIVITY_TYPES.map((t) => (
                          <SelectItem key={t} value={t} className="text-xs">
                            {ACTIVITY_TYPE_CONFIG[t].icon} {ACTIVITY_TYPE_CONFIG[t].label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <span className="text-muted-foreground text-xs">ekle</span>
                  </div>
                  <Textarea name="content" rows={2} placeholder="Notunuzu yazın…" className="text-sm" required />
                  <div className="flex justify-end">
                    <Button type="submit" size="sm" disabled={activityPending}>
                      {activityPending
                        ? <Loader2 className="size-3.5 animate-spin" />
                        : <MessageSquarePlus className="size-3.5" />}
                      Kaydet
                    </Button>
                  </div>
                </form>

                {/* Timeline */}
                <div className="space-y-3">
                  {activities.length === 0 && (
                    <p className="text-muted-foreground py-4 text-center text-sm">Henüz aktivite yok.</p>
                  )}
                  {activities.map((a) => {
                    const acfg = ACTIVITY_TYPE_CONFIG[a.type];
                    return (
                      <div key={a.id} className="flex gap-3">
                        <div className="bg-muted flex size-7 shrink-0 items-center justify-center rounded-full text-sm">
                          {acfg.icon}
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <span className="text-xs font-medium">{acfg.label}</span>
                            <span className="text-muted-foreground text-xs">
                              {formatDateTime(a.occurredAt ?? a.createdAt)}
                            </span>
                          </div>
                          <p className="mt-0.5 whitespace-pre-wrap text-sm">{a.content}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {tab === "followup" && (
              <form action={followUpAction} className="space-y-4 px-6 py-4">
                <input type="hidden" name="leadId" value={lead.id} />
                <div className="grid gap-2">
                  <Label htmlFor="followUpAt">Takip tarihi & saati</Label>
                  <Input
                    id="followUpAt"
                    name="followUpAt"
                    type="datetime-local"
                    min={new Date().toISOString().slice(0, 16)}
                    defaultValue={
                      lead.nextFollowUpAt
                        ? new Date(lead.nextFollowUpAt).toISOString().slice(0, 16)
                        : ""
                    }
                    required
                  />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="note">Not (isteğe bağlı)</Label>
                  <Textarea id="note" name="note" rows={2} placeholder="Görüşme konusu, hatırlatmalar…" />
                </div>
                <Button type="submit" className="w-full" disabled={followUpPending}>
                  {followUpPending
                    ? <><Loader2 className="size-4 animate-spin" />Planlanıyor…</>
                    : <><Calendar className="size-4" />Takvime ekle</>}
                </Button>
                {lead.nextFollowUpAt && (
                  <p className="text-muted-foreground text-center text-xs">
                    Mevcut takip: {formatDateTime(lead.nextFollowUpAt)}
                  </p>
                )}
              </form>
            )}
          </div>

          {/* Footer actions */}
          <div className="flex gap-2 border-t px-6 py-4">
            <Button variant="outline" size="sm" onClick={() => onEdit(lead)} className="flex-1">
              <ChevronDown className="size-3.5 rotate-90" />
              Düzenle
            </Button>
            {lead.status !== "converted" && lead.status !== "lost" && (
              <Button size="sm" onClick={handleConvert} disabled={convertBusy} className="flex-1 bg-green-600 hover:bg-green-700 text-white">
                {convertBusy
                  ? <Loader2 className="size-3.5 animate-spin" />
                  : <UserCheck className="size-3.5" />}
                Müşteriye dönüştür
              </Button>
            )}
            {lead.status === "converted" && (
              <div className="flex flex-1 items-center justify-center gap-1.5 text-sm text-green-600">
                <CheckCircle2 className="size-4" /> Müşteriye dönüştürüldü
              </div>
            )}
          </div>
        </div>
      </SheetContent>
    </Sheet>
  );
}
