"use client";

import * as React from "react";
import { useSession } from "next-auth/react";
import { toast } from "sonner";
import { Loader2, Save, Building2, Globe, AlertTriangle, X, Mail } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const ORG_TYPES = [
  { value: "personal", label: "Personal" },
  { value: "church", label: "Church" },
  { value: "ministry", label: "Ministry" },
  { value: "nonprofit", label: "Nonprofit" },
  { value: "other", label: "Other" },
];

type OrgData = {
  id: string;
  name: string;
  slug: string;
  type: string;
  timezone: string;
  allowedDomains: string[];
};

export default function OrganizationSettingsPage() {
  const { data: session } = useSession();
  const [org, setOrg] = React.useState<OrgData | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [domainInput, setDomainInput] = React.useState("");

  React.useEffect(() => {
    fetch("/api/org")
      .then((r) => r.json())
      .then((data) => {
        if (data.organization) setOrg(data.organization);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const handleSave = async () => {
    if (!org) return;
    setSaving(true);
    try {
      const res = await fetch("/api/org", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: org.name,
          type: org.type,
          timezone: org.timezone,
          allowedDomains: org.allowedDomains ?? [],
        }),
      });
      if (res.ok) {
        toast.success("Organization updated");
      } else {
        toast.error("Failed to update organization");
      }
    } catch {
      toast.error("Failed to update organization");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!org) {
    return (
      <div className="glass-card rounded-2xl p-8 text-center text-sm text-muted-foreground">
        No organization found. Complete onboarding to set up your organization.
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card className="glass-card">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Building2 className="size-4" />
            Organization Details
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Organization Name</Label>
            <Input
              value={org.name}
              onChange={(e) =>
                setOrg((prev) => (prev ? { ...prev, name: e.target.value } : prev))
              }
            />
          </div>
          <div className="space-y-2">
            <Label>URL Slug</Label>
            <Input value={org.slug} disabled className="opacity-60" />
            <p className="text-xs text-muted-foreground">
              The slug is auto-generated and cannot be changed.
            </p>
          </div>
          <div className="space-y-2">
            <Label>Type</Label>
            <Select
              value={org.type}
              onValueChange={(v) =>
                v && setOrg((prev) => (prev ? { ...prev, type: v } : prev))
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {ORG_TYPES.map((t) => (
                  <SelectItem key={t.value} value={t.value}>
                    {t.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Timezone</Label>
            <Input
              value={org.timezone}
              onChange={(e) =>
                setOrg((prev) =>
                  prev ? { ...prev, timezone: e.target.value } : prev
                )
              }
            />
          </div>
        </CardContent>
      </Card>

      <Card className="glass-card">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Mail className="size-4" />
            Allowed Email Domains
          </CardTitle>
          <CardDescription>
            Users who sign up with an email at these domains will automatically join this workspace.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {org.allowedDomains?.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {org.allowedDomains.map((domain) => (
                <span
                  key={domain}
                  className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-3 py-1 text-sm font-medium text-primary"
                >
                  {domain}
                  <button
                    type="button"
                    onClick={() =>
                      setOrg((prev) =>
                        prev
                          ? {
                              ...prev,
                              allowedDomains: prev.allowedDomains.filter(
                                (d) => d !== domain
                              ),
                            }
                          : prev
                      )
                    }
                    className="ml-0.5 rounded-full p-0.5 hover:bg-primary/20"
                  >
                    <X className="size-3" />
                  </button>
                </span>
              ))}
            </div>
          )}
          <div className="flex gap-2">
            <Input
              placeholder="example.com"
              value={domainInput}
              onChange={(e) => setDomainInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  const val = domainInput.trim().toLowerCase();
                  if (val && !org.allowedDomains?.includes(val)) {
                    setOrg((prev) =>
                      prev
                        ? {
                            ...prev,
                            allowedDomains: [...(prev.allowedDomains ?? []), val],
                          }
                        : prev
                    );
                    setDomainInput("");
                  }
                }
              }}
            />
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => {
                const val = domainInput.trim().toLowerCase();
                if (val && !org.allowedDomains?.includes(val)) {
                  setOrg((prev) =>
                    prev
                      ? {
                          ...prev,
                          allowedDomains: [...(prev.allowedDomains ?? []), val],
                        }
                      : prev
                  );
                  setDomainInput("");
                }
              }}
            >
              Add
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">
            Type a domain and press Enter or click Add. Changes are saved when you click Save Changes.
          </p>
        </CardContent>
      </Card>

      <div className="flex justify-end">
        <Button onClick={handleSave} disabled={saving}>
          {saving ? (
            <Loader2 className="mr-2 size-4 animate-spin" />
          ) : (
            <Save className="mr-2 size-4" />
          )}
          Save Changes
        </Button>
      </div>

      {/* Danger Zone */}
      <Card className="glass-card border-destructive/30">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base text-destructive">
            <AlertTriangle className="size-4" />
            Danger Zone
          </CardTitle>
          <CardDescription>
            These actions are irreversible and affect all members.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Button variant="destructive" size="sm" disabled>
            Delete Organization
          </Button>
          <p className="mt-2 text-xs text-muted-foreground">
            Organization deletion is not yet available. Contact support.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
