import React from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import {
  EmailTemplateBodyEditor,
  requiresAdvancedHtmlEditing,
  type EmailTemplateBodyEditorHandle,
} from '@/features/master/components/EmailTemplateBodyEditor';
import { Loader2, Play, Info, CheckCircle2, Settings, Edit2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
  composeEmailLayoutShell,
  parseEmailLayoutShell,
} from '@/features/master/utils/emailTemplateLayoutShell';

interface TemplateDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  editingTemplate: any;
  setEditingTemplate: (template: any) => void;
  testDataInput: string;
  setTestDataInput: (data: string) => void;
  previewLoading: boolean;
  handlePreviewTemplate: (body: string) => void;
  previewContent: any;
  handleSaveTemplate: (body: string) => void;
}

export const TemplateDialog: React.FC<TemplateDialogProps> = ({
  isOpen,
  onOpenChange,
  editingTemplate,
  setEditingTemplate,
  testDataInput,
  setTestDataInput,
  previewLoading,
  handlePreviewTemplate,
  previewContent,
  handleSaveTemplate,
}) => {
  const textareaRef = React.useRef<HTMLTextAreaElement>(null);
  const bodyEditorRef = React.useRef<EmailTemplateBodyEditorHandle>(null);
  const [bodyTab, setBodyTab] = React.useState<'visual' | 'html'>('visual');

  const [editableBody, setEditableBody] = React.useState('');
  const [shellMode, setShellMode] = React.useState(false);
  const [shellIncludesCta, setShellIncludesCta] = React.useState(false);

  React.useEffect(() => {
    if (!isOpen || !editingTemplate) return;
    const parsed = parseEmailLayoutShell(editingTemplate.body || '');
    setShellMode(parsed.isShellTemplate);
    setShellIncludesCta(parsed.includesCta);
    const nextEditable = parsed.isShellTemplate ? parsed.editableHtml : editingTemplate.body || '';
    setEditableBody(nextEditable);
    const preferHtml = requiresAdvancedHtmlEditing(nextEditable);
    setBodyTab(preferHtml ? 'html' : 'visual');
  }, [isOpen, editingTemplate?.id, editingTemplate?.body]);

  const composeFullBody = React.useCallback(() => {
    if (!shellMode) return editingTemplate?.body || '';
    return composeEmailLayoutShell(editableBody, shellIncludesCta);
  }, [shellMode, editableBody, shellIncludesCta, editingTemplate?.body]);

  const insertPlaceholder = (placeholder: string) => {
    bodyEditorRef.current?.insertPlaceholder(placeholder);
  };

  const placeholders = editingTemplate?.placeholders || [];

  const editorValue = shellMode ? editableBody : editingTemplate?.body || '';
  const onEditorChange = (html: string) => {
    if (shellMode) {
      setEditableBody(html);
      if (requiresAdvancedHtmlEditing(html)) setBodyTab('html');
    } else {
      setEditingTemplate({ ...editingTemplate!, body: html });
      if (requiresAdvancedHtmlEditing(html)) setBodyTab('html');
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-7xl w-full max-h-[95vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Edit Email Template</DialogTitle>
          <DialogDescription>Trigger codes are fixed by system seeding. Edit subject and message content below.</DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          <div className="lg:col-span-4 space-y-6">
            <div className="space-y-4">
              <div className="bg-slate-50 p-4 rounded-lg border border-slate-200 space-y-4">
                <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
                  <Settings className="w-4 h-4 text-re-red" />
                  General Settings
                </h3>
                <div>
                  <Label className="text-xs uppercase tracking-wider text-slate-500">Template Name</Label>
                  <Input
                    placeholder="e.g., Application Received"
                    className="mt-1.5 bg-white"
                    value={editingTemplate?.name || ''}
                    onChange={(e) => setEditingTemplate({ ...editingTemplate!, name: e.target.value })}
                  />
                </div>
                <div>
                  <Label className="text-xs uppercase tracking-wider text-slate-500">Trigger Code</Label>
                  <p className="text-[10px] text-slate-500 mt-1 mb-1">
                    Defined when the template row is seeded; it cannot be changed here.
                  </p>
                  <div className="mt-1.5 flex items-center">
                    <Badge variant="outline" className="bg-white font-mono text-xs px-3 py-1.5">
                      {editingTemplate?.templateCode || '—'}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label className="text-xs uppercase tracking-wider text-slate-500">Description</Label>
                  <Input
                    placeholder="Brief purpose of this email"
                    className="mt-1.5 bg-white"
                    value={editingTemplate?.description || ''}
                    onChange={(e) => setEditingTemplate({ ...editingTemplate!, description: e.target.value })}
                  />
                </div>
                <div className="flex items-center justify-between pt-2 border-t mt-2">
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="active"
                      checked={editingTemplate?.isActive ?? true}
                      onCheckedChange={(checked) => setEditingTemplate({ ...editingTemplate!, isActive: checked })}
                    />
                    <Label htmlFor="active" className="text-sm cursor-pointer">
                      Active
                    </Label>
                  </div>
                  <Badge
                    className={
                      editingTemplate?.isActive ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-500'
                    }
                  >
                    {editingTemplate?.isActive ? 'Template Enabled' : 'Template Disabled'}
                  </Badge>
                </div>
              </div>

              <div className="bg-red-50 p-4 rounded-lg border border-red-100">
                <h3 className="text-sm font-semibold text-red-900 flex items-center gap-2 mb-3">
                  <Info className="w-4 h-4" />
                  Available Placeholders
                </h3>
                <p className="text-[10px] text-re-red-hover mb-4 leading-relaxed">
                  Click a placeholder to insert it at the cursor.
                </p>
                <div className="flex flex-wrap gap-2">
                  {placeholders.length > 0 ? (
                    placeholders.map((p: string) => (
                      <button
                        key={p}
                        type="button"
                        onClick={() => insertPlaceholder(p)}
                        className="px-2 py-1 bg-white border border-red-200 rounded text-[11px] font-mono text-red-800 hover:bg-re-red hover:text-white hover:border-re-red transition-all flex items-center gap-1 shadow-sm"
                      >
                        {`{{${p}}}`}
                      </button>
                    ))
                  ) : (
                    <div className="w-full py-4 text-center border-2 border-dashed border-red-200 rounded-lg">
                      <p className="text-[10px] text-re-red">No placeholders defined for this trigger</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div className="lg:col-span-4 space-y-4 flex flex-col h-full min-h-[600px]">
            <div className="flex items-center justify-between">
              <h3 className="font-semibold text-slate-900 flex items-center gap-2">
                <Edit2 className="w-4 h-4 text-re-red" />
                Template Designer
              </h3>
            </div>

            <div className="flex-1 flex flex-col space-y-4">
              <div>
                <Label className="text-xs font-semibold">Subject Line</Label>
                <Input
                  placeholder="Subject line with {{variables}}"
                  className="mt-1.5 text-slate-900 font-medium"
                  value={editingTemplate?.subject || ''}
                  onChange={(e) => setEditingTemplate({ ...editingTemplate!, subject: e.target.value })}
                />
              </div>

              <div className="flex-1 flex flex-col min-h-[480px]">
                <Label className="text-xs font-semibold mb-1.5">Email Body</Label>
                <EmailTemplateBodyEditor
                  ref={bodyEditorRef}
                  tab={bodyTab}
                  onTabChange={(v) => setBodyTab(v as 'visual' | 'html')}
                  textareaRef={textareaRef}
                  value={editorValue}
                  onChange={onEditorChange}
                />
              </div>
            </div>
          </div>

          <div className="lg:col-span-4 space-y-6 lg:border-l lg:pl-8 flex flex-col h-full">
            <div>
              <h3 className="font-semibold text-slate-900 flex items-center gap-2 mb-4">
                <Play className="w-4 h-4 text-green-600" />
                Live Simulation
              </h3>

              <div className="space-y-4">
                <div>
                  <div className="flex items-center justify-between mb-1.5">
                    <Label className="text-xs font-semibold">Mock Test Data (JSON)</Label>
                    <button
                      type="button"
                      onClick={() =>
                        setTestDataInput(
                          '{"applicantName": "Rajesh Kumar", "location": "Mumbai South", "applicationId": "APP-2026-X12", "link": "https://example.com/app", "portalLink": "https://example.com/app"}'
                        )
                      }
                      className="text-[10px] text-re-red hover:underline"
                    >
                      Reset to Sample
                    </button>
                  </div>
                  <Textarea
                    placeholder='{"applicant_name": "John Doe"}'
                    className="font-mono text-[11px] text-slate-900 bg-slate-50"
                    rows={6}
                    value={testDataInput}
                    onChange={(e) => setTestDataInput(e.target.value)}
                  />
                </div>

                <Button
                  variant="default"
                  type="button"
                  className="w-full bg-green-600 hover:bg-green-700 shadow-md"
                  onClick={() => handlePreviewTemplate(composeFullBody())}
                  disabled={previewLoading}
                >
                  {previewLoading ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <Play className="w-4 h-4 mr-2" />
                  )}
                  Generate Mock Preview
                </Button>
              </div>
            </div>

            <div className="flex-1 flex flex-col">
              <Label className="text-xs font-semibold mb-2">Simulated Output</Label>
              <div className="flex-1 border rounded-xl overflow-hidden flex flex-col bg-slate-50 shadow-inner">
                {previewContent ? (
                  <>
                    <div className="bg-white p-3 border-b text-[11px] font-semibold text-slate-700 flex items-center justify-between">
                      <div className="truncate shrink">
                        <span className="text-slate-400 mr-2">Subject:</span> {previewContent.subject}
                      </div>
                      <Badge variant="outline" className="bg-green-50 text-green-600 text-[9px] whitespace-nowrap ml-2">
                        <CheckCircle2 className="w-3 h-3 mr-1" /> Compiled
                      </Badge>
                    </div>
                    <div className="p-6 bg-white overflow-auto flex-1 shadow-sm">
                      <div
                        className="max-w-none text-sm text-slate-800 email-preview-container"
                        dangerouslySetInnerHTML={{ __html: previewContent.html }}
                      />
                    </div>
                  </>
                ) : (
                  <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-slate-400 space-y-3">
                    <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center">
                      <Play className="w-8 h-8 opacity-20" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-slate-500">Ready for Preview</p>
                      <p className="text-[11px]">Click &quot;Generate Mock Preview&quot; to see the rendered email.</p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="flex gap-3 pt-4 border-t mt-4">
          <Button variant="outline" className="flex-1" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            className="flex-1 bg-re-red hover:bg-re-red-hover"
            type="button"
            onClick={() => handleSaveTemplate(composeFullBody())}
            disabled={!editingTemplate?.id || !editingTemplate?.templateCode?.trim()}
          >
            Save Template
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};
