"use client";

import { useActionState, useEffect } from "react";
import { toast } from "sonner";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ResponsiveSheet, FormWizard } from "@/components/ui/responsive-sheet";
import { createActivityAction, updateActivityAction } from "@/lib/appwrite/activity-actions";
import type { Activity, Customer, Property } from "@/lib/appwrite/schema";
import type { TenantRole } from "@/lib/appwrite/tenant-guard";

export type TeamMember = { id: string; name: string };

type ActionState = { ok: boolean; error?: string; fieldErrors?: Record<string, string[]> };
const INITIAL: ActionState = { ok: false };

interface ActivityFormSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  activity?: Activity | null;
  customers: Customer[];
  properties: Property[];
  members?: TeamMember[];
  role?: TenantRole;
  currentUserId?: string;
  onSuccess?: () => void;
}

export function ActivityFormSheet({ open, onOpenChange, activity, customers, properties, members, role, currentUserId, onSuccess }: ActivityFormSheetProps) {
  const action = activity ? updateActivityAction.bind(null, activity.$id) : createActivityAction;
  const [state, formAction, isPending] = useActionState(action, INITIAL);

  useEffect(() => {
    if (state.ok) {
      toast.success(activity ? "Aktivite güncellendi." : "Aktivite oluşturuldu.");
      onSuccess?.();
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  const fe = state.fieldErrors ?? {};

  const steps = [
    {
      label: "Aktivite",
      content: (
        <>
          <div className="grid grid-cols-3 gap-3">
            <div className="grid gap-1.5">
              <Label>Tip *</Label>
              <select name="type" defaultValue={activity?.type ?? "gorusme"}
                className="border-input bg-background h-9 rounded-md border px-3 text-sm">
                <option value="gorusme">Görüşme</option>
                <option value="teklif">Teklif</option>
                <option value="ziyaret">Ziyaret</option>
                <option value="arama">Arama</option>
                <option value="not">Not</option>
              </select>
            </div>
            <div className="col-span-2 grid gap-1.5">
              <Label htmlFor="title">Başlık *</Label>
              <Input id="title" name="title" defaultValue={activity?.title} placeholder="Görüşme notu..." />
              {fe.title && <p className="text-destructive text-xs">{fe.title[0]}</p>}
            </div>
          </div>
          <div className="grid gap-1.5">
            <Label htmlFor="dueDate">Tarih</Label>
            <Input id="dueDate" name="dueDate" type="date"
              defaultValue={activity?.dueDate ? activity.dueDate.split("T")[0] : ""} />
          </div>
          {(role === "owner" || role === "admin") && members && members.length > 0 && (
            <div className="grid gap-1.5">
              <Label>Atanan Kişi</Label>
              <select
                name="assigneeId"
                defaultValue={activity?.assigneeId ?? currentUserId ?? ""}
                className="border-input bg-background h-9 rounded-md border px-3 text-sm"
              >
                {members.map((m) => (
                  <option key={m.id} value={m.id}>
                    {m.id === currentUserId ? `${m.name} (ben)` : m.name}
                  </option>
                ))}
              </select>
            </div>
          )}
        </>
      ),
    },
    {
      label: "Bağlantı",
      content: (
        <>
          <div className="grid gap-1.5">
            <Label>Müşteri</Label>
            <select name="customerId" defaultValue={activity?.customerId ?? ""}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm">
              <option value="">Seçiniz</option>
              {customers.map((c) => (
                <option key={c.$id} value={c.$id}>{c.name}</option>
              ))}
            </select>
          </div>
          <div className="grid gap-1.5">
            <Label>İlan</Label>
            <select name="propertyId" defaultValue={activity?.propertyId ?? ""}
              className="border-input bg-background h-9 rounded-md border px-3 text-sm">
              <option value="">Seçiniz</option>
              {properties.map((p) => (
                <option key={p.$id} value={p.$id}>{p.title}</option>
              ))}
            </select>
          </div>
        </>
      ),
    },
    {
      label: "Detay",
      content: (
        <div className="grid gap-1.5">
          <Label htmlFor="description">Açıklama</Label>
          <Textarea id="description" name="description" rows={5} defaultValue={activity?.description ?? ""} />
        </div>
      ),
    },
  ];

  return (
    <ResponsiveSheet open={open} onOpenChange={onOpenChange}
      title={activity ? "Aktiviteyi Düzenle" : "Yeni Aktivite"}
      maxWidth="sm:max-w-lg">
      <form action={formAction}>
        <FormWizard steps={steps} isPending={isPending} submitLabel={activity ? "Güncelle" : "Oluştur"} />
      </form>
    </ResponsiveSheet>
  );
}
