"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/Button";
import { Card, CardHeader, CardTitle, Field, Label } from "@/components/ui/Card";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { StatCard } from "@/components/shared/StatCard";
import { sendElectionEmailCampaign } from "@/lib/actions/election-distribute";
import { saveAsTemplate } from "@/lib/actions/elections";
import { ElectionSharePanel } from "@/components/features/elections/ElectionSharePanel";
import { formatDate, formatNumber } from "@/lib/utils/format";

interface DeliveryRow {
  id: string;
  voterRollId: string;
  status: string;
  sentAt: Date | string;
  hasVoted: boolean;
  voterType: string | null;
}

interface DistributePanelProps {
  electionId: string;
  electionTitle: string;
  electionSlug: string;
  publicUrl: string;
  electionStatus: string;
  deliveries: DeliveryRow[];
  readOnly?: boolean;
}

export function DistributePanel({
  electionId,
  electionTitle,
  electionSlug,
  publicUrl,
  electionStatus,
  deliveries,
  readOnly,
}: DistributePanelProps) {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const [subject, setSubject] = useState(`Vote now: ${electionTitle}`);
  const [body, setBody] = useState(
    "You are invited to cast your ballot. Use the link below and verify with your email."
  );
  const [eligibilityStatus, setEligibilityStatus] = useState("eligible");
  const [templateName, setTemplateName] = useState(`${electionTitle} template`);

  const sent = deliveries.length;
  const voted = deliveries.filter((row) => row.status === "voted" || row.hasVoted)
    .length;

  function run(
    action: () => Promise<
      | { success: true; data?: unknown }
      | { success: false; error: string }
    >,
    successMessage?: string
  ) {
    setError(null);
    setMessage(null);
    startTransition(async () => {
      const result = await action();
      if (!result.success) {
        setError(result.error);
        return;
      }
      if (successMessage) setMessage(successMessage);
      router.refresh();
    });
  }

  return (
    <div className="space-y-5">
      <div className="grid gap-3 sm:grid-cols-3">
        <StatCard label="Invites logged" value={formatNumber(sent)} />
        <StatCard label="Voted from invite" value={formatNumber(voted)} />
        <StatCard
          label="Open rate proxy"
          value={sent === 0 ? "—" : `${Math.round((voted / sent) * 100)}%`}
        />
      </div>

      <ElectionSharePanel
        electionId={electionId}
        electionTitle={electionTitle}
        slug={electionSlug}
        publicUrl={publicUrl}
        electionStatus={electionStatus}
        readOnly={readOnly}
      />

      {!readOnly && (
        <Card className="p-5">
          <CardHeader className="mb-3 px-0 py-0">
            <CardTitle>Email campaign</CardTitle>
          </CardHeader>
          <div className="space-y-3">
            <Field>
              <Label>Subject</Label>
              <Input value={subject} onChange={(e) => setSubject(e.target.value)} />
            </Field>
            <Field>
              <Label>Message</Label>
              <textarea
                className="min-h-[120px] w-full rounded-lg border border-border px-3 py-2 text-[13px]"
                value={body}
                onChange={(e) => setBody(e.target.value)}
              />
            </Field>
            <Field>
              <Label>Audience</Label>
              <Select
                value={eligibilityStatus}
                onChange={(e) => setEligibilityStatus(e.target.value)}
              >
                <option value="eligible">Eligible voters</option>
                <option value="pending_authorization">Pending authorization</option>
                <option value="all">Everyone on the roll</option>
              </Select>
            </Field>
            <Button
              type="button"
              loading={isPending}
              disabled={electionStatus !== "open"}
              onClick={() =>
                run(
                  () =>
                    sendElectionEmailCampaign({
                      electionId,
                      subject,
                      body,
                      eligibilityStatus,
                    }),
                  "Campaign send finished"
                )
              }
            >
              Send invites
            </Button>
            {electionStatus !== "open" && (
              <p className="text-[12px] text-muted">
                Publish the election before sending invites.
              </p>
            )}
          </div>
        </Card>
      )}

      {!readOnly && (
        <Card className="p-5">
          <CardHeader className="mb-3 px-0 py-0">
            <CardTitle>Save as template</CardTitle>
          </CardHeader>
          <div className="flex flex-wrap items-end gap-3">
            <Field className="min-w-[220px] flex-1">
              <Label>Template name</Label>
              <Input
                value={templateName}
                onChange={(e) => setTemplateName(e.target.value)}
              />
            </Field>
            <Button
              type="button"
              variant="outline"
              loading={isPending}
              onClick={() =>
                run(
                  () => saveAsTemplate({ electionId, name: templateName }),
                  "Template saved"
                )
              }
            >
              Save template
            </Button>
          </div>
          <p className="mt-2 text-[12px] text-muted">
            Snapshots positions, eligibility model, and security config — not
            voters, candidates, or results.
          </p>
        </Card>
      )}

      <Card className="overflow-hidden">
        <CardHeader className="border-b border-border">
          <CardTitle>Recent deliveries</CardTitle>
        </CardHeader>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[520px] text-left text-[13px]">
            <thead className="bg-[#F8FAFC] text-[11px] uppercase tracking-wide text-muted">
              <tr>
                <th className="px-4 py-3 font-bold">Sent</th>
                <th className="px-4 py-3 font-bold">Roll</th>
                <th className="px-4 py-3 font-bold">Status</th>
                <th className="px-4 py-3 font-bold">Voted</th>
              </tr>
            </thead>
            <tbody>
              {deliveries.length === 0 ? (
                <tr>
                  <td colSpan={4} className="px-4 py-8 text-center text-muted">
                    No campaign deliveries yet.
                  </td>
                </tr>
              ) : (
                deliveries.map((delivery) => (
                  <tr key={delivery.id} className="border-t border-border">
                    <td className="px-4 py-3">{formatDate(delivery.sentAt)}</td>
                    <td className="px-4 py-3 font-mono text-[12px]">
                      {delivery.voterRollId.slice(0, 8)}…
                    </td>
                    <td className="px-4 py-3">{delivery.status}</td>
                    <td className="px-4 py-3">
                      {delivery.hasVoted || delivery.status === "voted"
                        ? "Yes"
                        : "No"}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {error && (
        <p className="rounded-md bg-danger-bg px-3 py-2 text-[13px] text-danger">
          {error}
        </p>
      )}
      {message && (
        <p className="rounded-md bg-success-bg px-3 py-2 text-[13px] text-success">
          {message}
        </p>
      )}
    </div>
  );
}
