import { ChevronDown } from 'lucide-react';
import { toast } from 'sonner';

import { useState } from 'react';

import { Head, router, useForm } from '@inertiajs/react';

import InputError from '@/Components/InputError';
import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { formatDateOnly } from '@/lib/format';

interface SiteGeneral {
  id: number;
  name: string;
  domain: string;
  created_at: string | null;
  is_owner: boolean;
  has_gsc_connection: boolean;
  has_wp_connection: boolean;
}

interface Props {
  site: SiteGeneral;
}

export default function SiteSettingsGeneral({ site }: Props) {
  const { data, setData, patch, processing, errors, isDirty } = useForm({
    name: site.name,
    domain: site.domain,
  });

  useUnsavedChanges(isDirty);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    patch(route('sites.update', site.id), { preserveScroll: true });
  };

  const domainChanged = data.domain !== site.domain;
  const hasConnections = site.has_gsc_connection || site.has_wp_connection;

  // Typed-confirmation delete: user must type the site domain to enable the button.
  // Danger Zone is collapsed by default so a day-one user isn't shown how to
  // delete everything immediately; they must click to reveal the section.
  const [dangerZoneOpen, setDangerZoneOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [confirmText, setConfirmText] = useState('');
  const [deleting, setDeleting] = useState(false);
  const confirmMatches = confirmText.trim() === site.domain;

  const handleDelete = () => {
    if (!confirmMatches) return;
    setDeleting(true);
    router.delete(route('sites.destroy', site.id), {
      preserveScroll: false,
      onError: () => toast.error('Could not delete the site. Please try again or contact support.'),
      onFinish: () => setDeleting(false),
    });
  };

  return (
    <>
      <Head title={`${site.name} — General settings`} />

      <EditorialPageHeader
        eyebrow={`Settings · ${site.name}`}
        title="General settings"
        subtitle={`Edit your site name and domain. ${!site.is_owner ? 'Only the site owner can delete this site.' : ''}`}
      />

      <div className="container py-8">
        <form onSubmit={handleSubmit} className="max-w-lg space-y-6">
          <div>
            <Label htmlFor="site-name" className="text-sm font-medium">
              Site name
            </Label>
            <p className="text-sm text-muted-foreground mt-0.5">
              Internal label — only visible to you and your team.
            </p>
            <Input
              id="site-name"
              type="text"
              value={data.name}
              onChange={(e) => setData('name', e.target.value)}
              maxLength={255}
              className="mt-2"
              autoComplete="off"
            />
            <InputError message={errors.name} className="mt-1" />
          </div>

          <div>
            <Label htmlFor="site-domain" className="text-sm font-medium">
              Domain
            </Label>
            <p className="text-sm text-muted-foreground mt-0.5">
              The full URL of the site you want to analyze, e.g. https://example.com.
            </p>
            <Input
              id="site-domain"
              type="url"
              value={data.domain}
              onChange={(e) => setData('domain', e.target.value)}
              maxLength={500}
              className="mt-2"
              inputMode="url"
              autoComplete="off"
            />
            <InputError message={errors.domain} className="mt-1" />

            {domainChanged && hasConnections && (
              <p className="mt-3 rounded-md border border-warning-border bg-warning-soft p-3 text-sm text-warning-strong">
                Changing the domain may require you to reconnect{' '}
                {site.has_gsc_connection && site.has_wp_connection
                  ? 'your Google Search Console and WordPress connections'
                  : site.has_gsc_connection
                    ? 'your Google Search Console connection'
                    : 'your WordPress connection'}
                .
              </p>
            )}
          </div>

          <LoadingButton loading={processing} disabled={!isDirty}>
            Save changes
          </LoadingButton>
        </form>

        {site.created_at && (
          <p className="text-xs text-muted-foreground mt-6">
            Site added on {formatDateOnly(site.created_at)}.
          </p>
        )}

        {/* Danger Zone — owner only. Collapsed by default so a day-one user
            isn't immediately shown how to delete their site. SitePolicy::delete
            enforces ownership server-side regardless of UI visibility. */}
        {site.is_owner && (
          <div className="mt-12 max-w-lg rounded-lg border border-destructive/30 bg-destructive/5 p-5">
            <button
              type="button"
              aria-expanded={dangerZoneOpen}
              aria-controls="danger-zone-content"
              onClick={() => setDangerZoneOpen((o) => !o)}
              className="flex w-full items-center justify-between rounded outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
            >
              <span className="text-base font-semibold text-destructive">Danger zone</span>
              <ChevronDown
                className={`size-4 text-destructive transition-transform duration-200 ${dangerZoneOpen ? 'rotate-180' : ''}`}
                aria-hidden="true"
              />
            </button>

            {dangerZoneOpen && (
              <div id="danger-zone-content" className="mt-3">
                <p className="text-sm text-muted-foreground">
                  Deleting this site permanently removes all analysis runs, recommendations, drafts,
                  snapshots, and connection metadata. This cannot be undone.
                </p>

                {!deleteOpen ? (
                  <Button
                    type="button"
                    variant="destructive"
                    className="mt-4"
                    onClick={() => setDeleteOpen(true)}
                  >
                    Delete this site
                  </Button>
                ) : (
                  <div className="mt-4 space-y-3">
                    <Label htmlFor="delete-confirm" className="text-sm font-medium">
                      Type <span className="font-data text-destructive">{site.domain}</span> to confirm.
                    </Label>
                    <Input
                      id="delete-confirm"
                      type="text"
                      value={confirmText}
                      onChange={(e) => setConfirmText(e.target.value)}
                      autoComplete="off"
                      aria-describedby="delete-confirm-hint"
                    />
                    <p id="delete-confirm-hint" className="text-xs text-muted-foreground">
                      This permanently deletes the site and all its data.
                    </p>
                    <div className="flex gap-2">
                      <Button
                        type="button"
                        variant="destructive"
                        disabled={!confirmMatches || deleting}
                        onClick={handleDelete}
                      >
                        {deleting ? 'Deleting…' : 'Delete site permanently'}
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        disabled={deleting}
                        onClick={() => {
                          setDeleteOpen(false);
                          setConfirmText('');
                        }}
                      >
                        Cancel
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </>
  );
}

SiteSettingsGeneral.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
