"use client";

import { useForm, type SubmitHandler, type Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
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 { chitFundSchema, type ChitFundInput } from "@/lib/validations/chit-fund";
import { useCreateChitFund } from "@/hooks/use-chit-funds";
import { useBankAccounts } from "@/hooks/use-bank-accounts";
import { toInputDate } from "@/lib/utils/format";
import { cn } from "@/lib/utils";
import { Users } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (v: boolean) => void;
}

const PERIOD_OPTIONS = [
  { value: "MONTHLY",  label: "Monthly"      },
  { value: "BIWEEKLY", label: "Every 2 weeks" },
  { value: "WEEKLY",   label: "Weekly"        },
];

export function ChitFundDialog({ open, onOpenChange }: Props) {
  const create              = useCreateChitFund();
  const { data: accounts = [] } = useBankAccounts();
  const today               = toInputDate(new Date());

  const form = useForm<ChitFundInput>({
    resolver: zodResolver(chitFundSchema) as Resolver<ChitFundInput>,
    defaultValues: {
      periodType:    "MONTHLY",
      currency:      "USD",
      startDate:     today,
      bankAccountId: null,
    },
  });

  const selectedAccountId  = form.watch("bankAccountId");
  const totalMembers       = form.watch("totalMembers")       ?? 0;
  const contributionCents  = form.watch("contributionCents")  ?? 0;
  const autoChitValue      = totalMembers * contributionCents;

  const onSubmit: SubmitHandler<ChitFundInput> = async (data) => {
    if (!data.chitValueCents && autoChitValue > 0) {
      data.chitValueCents = autoChitValue;
    }
    await create.mutateAsync(data);
    onOpenChange(false);
    form.reset();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-lg max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Users className="h-5 w-5 text-violet-400" />
            Add Chit Fund / ROSCA
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 mt-2">

          {/* Name + Organizer */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Fund Name</Label>
              <Input
                {...form.register("name")}
                placeholder="e.g. Office Chit 2025"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
              {form.formState.errors.name && (
                <p className="text-red-400 text-xs">{form.formState.errors.name.message}</p>
              )}
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Organizer (optional)</Label>
              <Input
                {...form.register("organizer")}
                placeholder="e.g. Ravi Kumar"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          {/* Members + Period */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Total Members</Label>
              <Input
                type="number"
                min={2}
                max={200}
                {...form.register("totalMembers", { valueAsNumber: true })}
                placeholder="20"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
              {form.formState.errors.totalMembers && (
                <p className="text-red-400 text-xs">{form.formState.errors.totalMembers.message}</p>
              )}
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Period</Label>
              <select
                {...form.register("periodType")}
                className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
              >
                {PERIOD_OPTIONS.map((o) => (
                  <option key={o.value} value={o.value}>{o.label}</option>
                ))}
              </select>
            </div>
          </div>

          {/* Contribution + Chit Value */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Your Contribution</Label>
              <Input
                type="number"
                step="0.01"
                {...form.register("contributionCents", {
                  setValueAs: (v) => Math.round(parseFloat(v) * 100),
                })}
                placeholder="500.00"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
              {form.formState.errors.contributionCents && (
                <p className="text-red-400 text-xs">{form.formState.errors.contributionCents.message}</p>
              )}
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">
                Chit Value
                {autoChitValue > 0 && (
                  <span className="text-slate-500 font-normal ml-1 text-xs">
                    (auto: {(autoChitValue / 100).toLocaleString()})
                  </span>
                )}
              </Label>
              <Input
                type="number"
                step="0.01"
                {...form.register("chitValueCents", {
                  setValueAs: (v) => v ? Math.round(parseFloat(v) * 100) : autoChitValue,
                })}
                placeholder={autoChitValue > 0 ? (autoChitValue / 100).toString() : "10000.00"}
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          {/* Currency + Start Date */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">Currency</Label>
              <select
                {...form.register("currency")}
                className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
              >
                {["USD","EUR","GBP","LKR","INR","SGD","AUD","CAD"].map((c) => (
                  <option key={c} value={c}>{c}</option>
                ))}
              </select>
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Start Date</Label>
              <Input
                type="date"
                {...form.register("startDate")}
                className="bg-slate-800 border-slate-600 text-white"
              />
            </div>
          </div>

          {/* My Turn + Expected Payout */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <Label className="text-slate-300">My Turn Number <span className="text-slate-500 font-normal">(optional)</span></Label>
              <Input
                type="number"
                min={1}
                {...form.register("myTurnNumber", {
                  setValueAs: (v) => v ? parseInt(v) : null,
                })}
                placeholder="e.g. 5"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
              <p className="text-xs text-slate-600">Which period you receive the pot</p>
            </div>
            <div className="space-y-1">
              <Label className="text-slate-300">Expected Payout <span className="text-slate-500 font-normal">(optional)</span></Label>
              <Input
                type="number"
                step="0.01"
                {...form.register("myPayoutCents", {
                  setValueAs: (v) => v ? Math.round(parseFloat(v) * 100) : null,
                })}
                placeholder="After auction discount"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>
          </div>

          {/* Linked Bank Account */}
          <div className="space-y-2">
            <Label className="text-slate-300 flex items-center gap-1.5">
              Linked Bank Account
              <span className="text-slate-500 font-normal text-xs">— contributions will debit this account</span>
            </Label>
            <div className="flex flex-wrap gap-2">
              <button
                type="button"
                onClick={() => form.setValue("bankAccountId", null)}
                className={cn(
                  "px-3 py-1.5 rounded-lg text-xs font-medium border transition-all",
                  !selectedAccountId
                    ? "bg-slate-600 border-slate-500 text-white"
                    : "bg-slate-800 border-slate-700 text-slate-400 hover:border-slate-600"
                )}
              >
                None
              </button>
              {accounts.map((acc) => (
                <button
                  key={acc.id}
                  type="button"
                  onClick={() => form.setValue("bankAccountId", acc.id)}
                  className={cn(
                    "px-3 py-1.5 rounded-lg text-xs font-medium border transition-all flex items-center gap-1.5",
                    selectedAccountId === acc.id
                      ? "border-transparent text-white"
                      : "bg-slate-800 border-slate-700 text-slate-400 hover:border-slate-600"
                  )}
                  style={selectedAccountId === acc.id ? {
                    backgroundColor: `${acc.color ?? "#7c3aed"}25`,
                    borderColor:     `${acc.color ?? "#7c3aed"}60`,
                    color:           acc.color ?? "#a78bfa",
                  } : undefined}
                >
                  <span className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: acc.color ?? "#7c3aed" }} />
                  {acc.name}
                </button>
              ))}
            </div>
          </div>

          {/* Notes */}
          <div className="space-y-1">
            <Label className="text-slate-300">Notes (optional)</Label>
            <Textarea
              {...form.register("notes")}
              placeholder="Any details about the group…"
              rows={2}
              className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500 resize-none"
            />
          </div>

          <div className="flex gap-3 pt-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              className="flex-1 border-slate-600 text-slate-300 hover:bg-slate-800"
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={create.isPending}
              className="flex-1 bg-violet-600 hover:bg-violet-500 text-white"
            >
              {create.isPending ? "Creating…" : "Add Chit Fund"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
