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

import SiteNav from '@/Components/Navigation/SiteNav';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Switch } from '@/Components/ui/switch';
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { formatDate } from '@/lib/format';
import type { SiteBasic } from '@/types';

interface Schedule {
  id: number;
  site_id: number;
  frequency: string;
  next_run_at: string | null;
  last_run_at: string | null;
  last_run_status: string | null;
  enabled: boolean;
}

interface AutomationSettings {
  auto_analyze_after_sync: boolean;
  auto_generate_drafts: boolean;
  draft_impact_threshold: number;
  min_analysis_interval_hours: number;
}

interface Props {
  site: SiteBasic;
  schedule: Schedule | null;
  automation: AutomationSettings;
}

export default function SiteSettings({ site, schedule, automation }: Props) {
  const { data, setData, patch, processing, errors, isDirty } = useForm({
    enabled: schedule?.enabled ?? false,
    frequency: schedule?.frequency ?? 'weekly',
  });

  const {
    data: automationData,
    setData: setAutomationData,
    patch: patchAutomation,
    processing: automationProcessing,
    errors: automationErrors,
    isDirty: isAutomationDirty,
  } = useForm<AutomationSettings>({
    auto_analyze_after_sync: automation.auto_analyze_after_sync,
    auto_generate_drafts: automation.auto_generate_drafts,
    draft_impact_threshold: automation.draft_impact_threshold,
    min_analysis_interval_hours: automation.min_analysis_interval_hours,
  });

  useUnsavedChanges(isDirty || isAutomationDirty);

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

  const handleAutomationSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    patchAutomation(route('sites.automation.update', site.id));
  };

  return (
    <>
      <Head title={`${site.name} - Analysis Schedule`} />

      <div className="container py-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        <h1 className="text-2xl font-bold tracking-tight">Analysis Schedule</h1>
        <p className="text-muted-foreground mt-1">
          Configure automatic analysis runs for {site.name}.
        </p>

        <form onSubmit={handleSubmit} className="max-w-lg space-y-6 mt-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label htmlFor="schedule-enabled" className="text-sm font-medium">
                  Enable scheduled analysis
                </Label>
                <p className="text-sm text-muted-foreground">
                  Automatically run analysis at regular intervals
                </p>
              </div>
              <Switch
                id="schedule-enabled"
                checked={data.enabled}
                onCheckedChange={(checked) => setData('enabled', checked)}
              />
            </div>
            {errors.enabled && <p className="text-sm text-destructive">{errors.enabled}</p>}
          </div>

          {data.enabled && (
            <div>
              <Label htmlFor="schedule-frequency" className="text-sm font-medium">
                Analysis frequency
              </Label>
              <Select value={data.frequency} onValueChange={(value) => setData('frequency', value)}>
                <SelectTrigger id="schedule-frequency" className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="daily">Daily</SelectItem>
                  <SelectItem value="weekly">Weekly</SelectItem>
                  <SelectItem value="bi-weekly">Bi-weekly (every 2 weeks)</SelectItem>
                  <SelectItem value="monthly">Monthly</SelectItem>
                </SelectContent>
              </Select>
              {errors.frequency && (
                <p className="text-sm text-destructive mt-1">{errors.frequency}</p>
              )}
            </div>
          )}

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

        {schedule && (
          <div className="max-w-lg mt-8 p-4 border rounded-lg bg-muted/50">
            <h2 className="text-sm font-medium mb-3">Schedule Information</h2>
            <dl className="space-y-2 text-sm">
              {schedule.next_run_at && (
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Next scheduled run:</dt>
                  <dd className="font-medium">{formatDate(schedule.next_run_at)}</dd>
                </div>
              )}
              {schedule.last_run_at && (
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Last run:</dt>
                  <dd className="font-medium">{formatDate(schedule.last_run_at)}</dd>
                </div>
              )}
              {schedule.last_run_status && (
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Last run status:</dt>
                  <dd className="font-medium capitalize">{schedule.last_run_status}</dd>
                </div>
              )}
            </dl>
          </div>
        )}

        {/* Automation Settings */}
        <div className="mt-10 border-t pt-10">
          <h2 className="text-xl font-bold tracking-tight">Automation</h2>
          <p className="text-muted-foreground mt-1">
            Configure automated SEO workflows that run without manual intervention.
          </p>

          <form onSubmit={handleAutomationSubmit} className="max-w-lg space-y-6 mt-6">
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="auto-analyze" className="text-sm font-medium">
                    Auto-analyze after GSC sync
                  </Label>
                  <p className="text-sm text-muted-foreground">
                    Automatically run analysis after each Google Search Console sync
                  </p>
                </div>
                <Switch
                  id="auto-analyze"
                  checked={automationData.auto_analyze_after_sync}
                  onCheckedChange={(checked) =>
                    setAutomationData('auto_analyze_after_sync', checked)
                  }
                />
              </div>
              {automationErrors.auto_analyze_after_sync && (
                <p className="text-sm text-destructive">
                  {automationErrors.auto_analyze_after_sync}
                </p>
              )}
            </div>

            {automationData.auto_analyze_after_sync && (
              <div>
                <label htmlFor="min-interval" className="text-sm font-medium">
                  Minimum interval between analyses (hours)
                </label>
                <Input
                  id="min-interval"
                  type="number"
                  min={1}
                  max={168}
                  value={automationData.min_analysis_interval_hours}
                  onChange={(e) =>
                    setAutomationData(
                      'min_analysis_interval_hours',
                      parseInt(e.target.value, 10) || 1,
                    )
                  }
                  className="mt-1"
                />
                {automationErrors.min_analysis_interval_hours && (
                  <p className="text-sm text-destructive mt-1">
                    {automationErrors.min_analysis_interval_hours}
                  </p>
                )}
              </div>
            )}

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <label htmlFor="auto-drafts" className="text-sm font-medium">
                    Auto-generate content drafts
                  </label>
                  <p className="text-sm text-muted-foreground">
                    Automatically generate AI drafts for high-impact keyword opportunities
                  </p>
                </div>
                <Switch
                  id="auto-drafts"
                  checked={automationData.auto_generate_drafts}
                  onCheckedChange={(checked) => setAutomationData('auto_generate_drafts', checked)}
                />
              </div>
              {automationErrors.auto_generate_drafts && (
                <p className="text-sm text-destructive">{automationErrors.auto_generate_drafts}</p>
              )}
            </div>

            {automationData.auto_generate_drafts && (
              <div>
                <label htmlFor="impact-threshold" className="text-sm font-medium">
                  Minimum impact score for draft generation (0–100)
                </label>
                <p className="text-sm text-muted-foreground mt-0.5">
                  Only opportunities above this threshold will receive auto-generated drafts
                </p>
                <Input
                  id="impact-threshold"
                  type="number"
                  min={0}
                  max={100}
                  value={automationData.draft_impact_threshold}
                  onChange={(e) =>
                    setAutomationData('draft_impact_threshold', parseInt(e.target.value, 10) || 0)
                  }
                  className="mt-1"
                />
                {automationErrors.draft_impact_threshold && (
                  <p className="text-sm text-destructive mt-1">
                    {automationErrors.draft_impact_threshold}
                  </p>
                )}
              </div>
            )}

            <LoadingButton loading={automationProcessing} disabled={!isAutomationDirty}>
              Save Automation Settings
            </LoadingButton>
          </form>
        </div>
      </div>
    </>
  );
}

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