'use client';
import { useState } from 'react';
import type { CopyWeekResult, Membership, ScheduleWeek } from '@alqove/api-client';
import { useCopyWeek, useScheduleMutation } from '@/lib/queries/use-scheduling';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { addDays, instantToLocal } from './schedule-time';
import { scheduleError } from './schedule-feedback';

export function WeekActions({ membership, week, onSelectWeek }: { membership: Membership; week: ScheduleWeek; onSelectWeek: (date: string) => void }) {
  const [dialog, setDialog] = useState<'copy' | 'publish' | null>(null);
  const [copied, setCopied] = useState<CopyWeekResult | null>(null);
  return <div className="flex flex-wrap gap-2">
    {membership.capabilities.includes('schedule.manage') && <Button variant="outline" onClick={() => { setCopied(null); setDialog('copy'); }}>Copy week</Button>}
    {membership.capabilities.includes('schedule.publish') && <Button onClick={() => setDialog('publish')}>Publish week</Button>}
    {membership.capabilities.includes('settings.schedule') && <a className="self-center text-sm underline" href="/seller/settings/schedule">Schedule settings</a>}
    {copied && <p role="status" className="w-full text-sm">Copy committed: {copied.copied} draft shifts in week {copied.target_week_start}. <button className="underline" onClick={() => onSelectWeek(copied.target_week_start)}>View copied week</button></p>}
    {dialog === 'copy' && <CopyWeekDialog storeId={membership.store_id} week={week} onClose={() => setDialog(null)} onCommitted={setCopied} />}
    {dialog === 'publish' && <PublishWeekDialog storeId={membership.store_id} week={week} onClose={() => setDialog(null)} />}
  </div>;
}
function CopyWeekDialog({ storeId, week, onClose, onCommitted }: { storeId: string; week: ScheduleWeek; onClose: () => void; onCommitted: (result: CopyWeekResult) => void }) {
  const [source, setSource] = useState(week.week_start);
  const [target, setTarget] = useState(addDays(week.week_start, 7));
  const [preview, setPreview] = useState<CopyWeekResult | null>(null);
  const [error, setError] = useState('');
  const mutation = useCopyWeek(storeId);
  const copy = async (isPreview: boolean) => {
    setError('');
    if (!isPreview && (!preview || preview.conflict_count > 0)) return;
    try {
      const response = await mutation.mutateAsync({ source_week_start: source, target_week_start: target, preview: isPreview });
      if (isPreview) setPreview(response.data); else { onCommitted(response.data); onClose(); }
    } catch (e) { setPreview(null); setError(scheduleError(e)); }
  };
  return <Dialog open onOpenChange={open => { if (!open && !mutation.isPending) onClose(); }}><DialogContent className="max-h-[90dvh] overflow-y-auto">
    <DialogTitle>Copy week</DialogTitle>
    <DialogDescription>Copy shifts as drafts in {week.timezone}. Preview the exact dates and times, including clock changes. The server rechecks current shifts and overlaps at commit; this preview does not reserve them.</DialogDescription>
    <form className="grid gap-4" onSubmit={e => { e.preventDefault(); void copy(true); }}>
      <fieldset disabled={mutation.isPending} className="grid gap-3 sm:grid-cols-2">
        <label className="grid gap-1">Source week<input className="min-w-0 rounded border p-2" required type="date" value={source} onChange={e => { setSource(e.target.value); setPreview(null); }} /></label>
        <label className="grid gap-1">Target week<input className="min-w-0 rounded border p-2" required type="date" value={target} onChange={e => { setTarget(e.target.value); setPreview(null); }} /></label>
      </fieldset>
      {error && <p role="alert" className="text-red-700">{error}</p>}
      {preview && <section aria-label="Copy preview" className="space-y-3">
        <p role="status">{preview.shift_count} shifts · {preview.conflict_count} conflicts</p>
        <p className="text-sm">{preview.source_week_start} → {preview.target_week_start}</p>
        {preview.conflicts.map((c, i) => <p key={i} className="text-red-700">{c.message} (source {c.source_shift_id})</p>)}
        <ul className="max-h-64 space-y-2 overflow-auto">{preview.shifts.map((s, i) => <li className="rounded border p-2 text-sm" key={i}>
          <strong>{s.member_name ?? 'Open shift'}</strong>{s.position_name && ` · ${s.position_name}`}<br />
          {instantToLocal(s.starts_at, week.timezone).replace('T', ' ')} → {instantToLocal(s.ends_at, week.timezone).replace('T', ' ')}
        </li>)}</ul>
      </section>}
      <div className="flex flex-wrap gap-2"><Button type="submit" variant="outline" disabled={mutation.isPending || source === target}>Preview copy</Button>
        {preview && <Button type="button" disabled={mutation.isPending || preview.conflict_count > 0 || !preview.shift_count} onClick={() => void copy(false)}>Commit copy</Button>}
        <Button type="button" variant="outline" disabled={mutation.isPending} onClick={onClose}>Cancel</Button></div>
    </form>
  </DialogContent></Dialog>;
}
function PublishWeekDialog({ storeId, week, onClose }: { storeId: string; week: ScheduleWeek; onClose: () => void }) {
  const mutation = useScheduleMutation(storeId);
  const [error, setError] = useState('');
  return <Dialog open onOpenChange={open => { if (!open && !mutation.isPending) onClose(); }}><DialogContent>
    <DialogTitle>Publish week</DialogTitle>
    <DialogDescription>Make the current shifts for the week of {week.week_start} visible to staff. Later edits become drafts and need publishing again.</DialogDescription>
    {error && <p role="alert" className="text-red-700">{error}</p>}
    <div className="flex gap-2"><Button disabled={mutation.isPending} onClick={async () => {
      try { await mutation.mutateAsync({ action: 'publish', week: week.week_start }); onClose(); }
      catch (e) { setError(scheduleError(e)); }
    }}>Confirm publish</Button><Button variant="outline" disabled={mutation.isPending} onClick={onClose}>Cancel</Button></div>
  </DialogContent></Dialog>;
}
